在 if-else 语句中使用 grep

Ada*_*ser 10 shell-script

如果输入的字符串不在文件中,为什么我的代码不输出。当我输入一个字符串并且它不在文件中时,没有响应,它重新循环回到开头。有人可以告诉我我的代码有什么问题吗?

while :
do
echo "Please enter a string"
read input_string
echo "Please enter the file name too see if that string is present in it - (Enter .abw after)"
read input_string1
if grep -q $input_string $input_string1 ; then
echo  "Your string has been found"
fi
done
Run Code Online (Sandbox Code Playgroud)

GMa*_*ter 10

while :
 do
     echo "Please enter a string"
     read input_string
     echo "Please enter the file name too see if that string is present in it - (Enter .abw after)"
     read input_string1
     grep -q "${input_string}" "${input_string1}"                                                                 
     if [ $? -eq 0 ] ; then
         echo  "Your string has been found"
     else 
         echo "Your string has not been found"
     fi
 done
Run Code Online (Sandbox Code Playgroud)

  • 您需要引用 grep 参数。想想如果我的搜索字符串包含“-v”,或者文件名中有空格会发生什么。 (2认同)