Bash grep 结果的条件 'OR'
Bash conditional 'OR' of grep results
我正在尝试对 bash 脚本中的两个 grep 命令的结果进行条件检查,但我似乎无法像这样组合它们:
if [[ $( stout_cmd1 | grep -q 'check_txt1' ) || ( $( stdout_cmd2 | grep -q 'check_txt2' ) ]] ; then
//do something here if output of stdout_cmdX contains text check_txtX
fi
因为它总是 returns 错误。有条件地检查命令是否按预期工作:
if stdout_cmd1 | grep -q 'check_txt1' ; then
或
if stdout_cmd2 | grep -q 'check_txt2' ; then
我不知道如何检查其中一个是否为真。如何在条件检查中组合两个标准输出输出?我已经从 grep 调用中删除了 -q
标志,但没有任何效果。
实际上你只是直接使用grep
的exit-code
运行沉默-q
if cmd1 | grep -q "check_txt1" || cmd2 | grep -q "check_txt2"
then
echo "Your code here!"
fi
[[
复合命令计算条件表达式,但您只需要管道的结果。您需要使用 ||
:
将两个管道合并到 list 中
if stout_cmd1 | grep -q 'check_txt1' || stdout_cmd2 | grep -q 'check_txt2'
then
# your code here
fi
来自 Bash 手册:
A list is a sequence of one or more pipelines separated by one of the operators ;
, &
, &&
, or ||
, and optionally terminated by one of ;
, &
, or <newline>
.
...
The return status of AND and OR lists is the exit status of the last command executed in the list.
示范[=29=]
#!/bin/sh
for i in 00 01 02 12
do
if echo "$i" | grep -q '1' || echo "$i" | grep -q '2'
then
echo "$i contains a 1 or 2"
else
echo "$i contains neither 1 nor 2"
fi
done
这会产生以下输出:
00 contains neither 1 nor 2
01 contains a 1 or 2
02 contains a 1 or 2
12 contains a 1 or 2
我正在尝试对 bash 脚本中的两个 grep 命令的结果进行条件检查,但我似乎无法像这样组合它们:
if [[ $( stout_cmd1 | grep -q 'check_txt1' ) || ( $( stdout_cmd2 | grep -q 'check_txt2' ) ]] ; then
//do something here if output of stdout_cmdX contains text check_txtX
fi
因为它总是 returns 错误。有条件地检查命令是否按预期工作:
if stdout_cmd1 | grep -q 'check_txt1' ; then
或
if stdout_cmd2 | grep -q 'check_txt2' ; then
我不知道如何检查其中一个是否为真。如何在条件检查中组合两个标准输出输出?我已经从 grep 调用中删除了 -q
标志,但没有任何效果。
实际上你只是直接使用grep
的exit-code
运行沉默-q
if cmd1 | grep -q "check_txt1" || cmd2 | grep -q "check_txt2"
then
echo "Your code here!"
fi
[[
复合命令计算条件表达式,但您只需要管道的结果。您需要使用 ||
:
if stout_cmd1 | grep -q 'check_txt1' || stdout_cmd2 | grep -q 'check_txt2'
then
# your code here
fi
来自 Bash 手册:
A list is a sequence of one or more pipelines separated by one of the operators
;
,&
,&&
, or||
, and optionally terminated by one of;
,&
, or<newline>
.
...
The return status of AND and OR lists is the exit status of the last command executed in the list.
示范[=29=]
#!/bin/sh
for i in 00 01 02 12
do
if echo "$i" | grep -q '1' || echo "$i" | grep -q '2'
then
echo "$i contains a 1 or 2"
else
echo "$i contains neither 1 nor 2"
fi
done
#!/bin/sh
for i in 00 01 02 12
do
if echo "$i" | grep -q '1' || echo "$i" | grep -q '2'
then
echo "$i contains a 1 or 2"
else
echo "$i contains neither 1 nor 2"
fi
done
这会产生以下输出:
00 contains neither 1 nor 2
01 contains a 1 or 2
02 contains a 1 or 2
12 contains a 1 or 2