Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell命令-基于命令输出的条件?_Shell_Conditional Statements - Fatal编程技术网

Shell命令-基于命令输出的条件?

Shell命令-基于命令输出的条件?,shell,conditional-statements,Shell,Conditional Statements,如果文本文件中没有字符串,我将尝试运行一些shell命令。如果我将这一行粘贴到命令行中,If会给我一个错误 if [ $(cat textfile.txt | grep "search string") -eq "" ]; then; echo "some string"; fi; 错误: -bash: [: -eq: unary operator expected 如果找到请求的行,grep命令将返回0(如果没有,则返回1;如果出错,则返回2),因此您可以使用: grep "search

如果文本文件中没有字符串,我将尝试运行一些shell命令。如果我将这一行粘贴到命令行中,If会给我一个错误

if [ $(cat textfile.txt | grep "search string") -eq "" ]; then; echo "some string"; fi;
错误:

-bash: [: -eq: unary operator expected

如果找到请求的行,
grep
命令将返回0(如果没有,则返回1;如果出错,则返回2),因此您可以使用:

grep "search string" textfile.txt >/dev/null 2>&1
if [[ $? -ne 0 ]] ; then
    echo 'Not found'
fi
如果您真的想使用字符串(而且可能不应该),那么应该引用它们,这样就不会为
[
命令获取太多参数:

if [ "$(cat textfile.txt | grep 'search string')" == "" ] ; then
    echo "It's not there!"
fi

如果使用
[]
进行比较,则需要使用
=
而不是
-eq
。还需要一些引号

if [ "$(cat textfile.txt | grep 'search string')" = "" ]; then; echo "some string"; fi;
请注意,
grep
可以将文件名作为参数,因此不需要使用
cat
。您也可以直接使用
grep
的返回值:如果未找到搜索字符串,grep将返回1

if [ "$(grep 'search string' textfile.txt)" ]; then
  echo "some string";
fi
一种更简洁的方法是使用逻辑and和
&&

grep "search string" textfile.txt && echo "some string"
注:

  • -F
    阻止将搜索字符串解释为正则表达式
  • -q
    在找到第一个实例后立即抑制所有输出并返回,如果字符串出现在大文件的开头,则搜索速度会更快
  • -e
    明确指定模式,允许以破折号开头的模式
  • 除非需要变量替换,否则请使用单引号

在这种情况下不需要方括号。因为
[
实际上是一个命令,任何命令都可以在您想要使用它的地方使用。所以在这里,我们可以使用
grep
。没有必要使用
cat
,因为
grep
将接受文件名作为参数。另外,您有两个太多的分号

if grep -q "search string" textfile.txt; then echo "some string"; fi


优雅。在某种程度上,有人试图将bash转换成perl
[[$(
不幸的是,我没有投反对票,但你的答案远非最优:没有必要进行重定向,因为
grep
有一个
-q
选项,Bash可以测试命令的返回值,而无需诉诸
$?
。没关系,飞利浦。并非所有grep都有这些选项(我仍然使用一些传统的Unix),无论如何,为了提高效率,我不会使用shell脚本。我将在将来将您的答案合并到我的(现代)脚本中,因此+1。您不必更改引号,这是非常有效的bash:
“$(cat textfile.txt|grep“search string”)”
if grep -q "search string" textfile.txt; then echo "some string"; fi
if grep "search string" textfile.txt > /dev/null 2>&1; then echo "some string"; fi