我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码出了什么问题?
我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码出了什么问题?
当前回答
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"
其他回答
if grep -q SomeString "$File"; then
Some Actions # SomeString was found
fi
这里不需要[[]]。直接执行命令即可。添加-q选项时,您不需要显示当它被找到的字符串。
grep命令在退出码中返回0或1,具体取决于 搜索的结果。如果发现了什么,则为0;否则1。
$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0
您可以指定命令作为if的条件。如果该命令在其exitcode中返回0,则意味着条件为真;否则错误。
$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$
如您所见,您在这里直接运行程序。没有附加的[]或[[]]。
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"
grep -q [PATTERN] [FILE] && echo $?
如果找到模式,则退出状态为0 (true);否则blankstring。
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; test $? -eq 0 && echo "yes" || echo "no"
但在这种情况下,你不需要显式地测试它,所以对:
grep -q "something" file && echo "yes" || echo "no"