我想在 bash 中检查文件是否包含特定字符串。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码有什么问题?
最佳答案
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
的条件。如果命令在其退出代码中返回 0,则表示条件为真;否则为假。
$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$
如您所见,您可以直接在此处运行程序。没有额外的 []
或 [[]]
。
关于bash - 如何使用 Bash 检查文件是否包含特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11287861/