我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:

 if [[ 'grep 'SomeString' $File' ]];then
   # Some Actions
 fi

我的代码出了什么问题?


当前回答

如果你想检查字符串是否匹配整行,如果它是一个固定的字符串,你可以这样做

grep -Fxq [String] [filePath]

例子

 searchString="Hello World"
 file="./test.log"
 if grep -Fxq "$searchString" $file
    then
            echo "String found in $file"
    else
            echo "String not found in $file"
 fi

从男子档案中可以看出:

-F, --fixed-strings

          Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of 

which is to be matched.
          (-F is specified by POSIX.)
-x, --line-regexp
          Select only those matches that exactly match the whole line.  (-x is specified by 

POSIX.)
-q, --quiet, --silent
          Quiet; do not write anything to standard output.  Exit immediately with zero 

status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages 

option.  (-q is specified by
          POSIX.)

其他回答

grep -q [PATTERN] [FILE] && echo $?

如果找到模式,则退出状态为0 (true);否则blankstring。

如果你想检查字符串是否匹配整行,如果它是一个固定的字符串,你可以这样做

grep -Fxq [String] [filePath]

例子

 searchString="Hello World"
 file="./test.log"
 if grep -Fxq "$searchString" $file
    then
            echo "String found in $file"
    else
            echo "String not found in $file"
 fi

从男子档案中可以看出:

-F, --fixed-strings

          Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of 

which is to be matched.
          (-F is specified by POSIX.)
-x, --line-regexp
          Select only those matches that exactly match the whole line.  (-x is specified by 

POSIX.)
-q, --quiet, --silent
          Quiet; do not write anything to standard output.  Exit immediately with zero 

status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages 

option.  (-q is specified by
          POSIX.)
if grep -q [string] [filename]
then
    [whatever action]
fi

例子

if grep -q 'my cat is in a tree' /tmp/cat.txt
then
    mkdir cat
fi
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"

最短(正确)版本:

grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"

也可以写成

grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"

但在这种情况下,你不需要显式地测试它,所以对:

grep -q "something" file && echo "yes" || echo "no"