Reputation: 483
I am trying to do a conditional check of the result of two grep commands in a bash script, but I cannot seem to combine them like:
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
as it always returns false. Conditionally checking the commands on their own work as intended:
if stdout_cmd1 | grep -q 'check_txt1' ; then
or
if stdout_cmd2 | grep -q 'check_txt2' ; then
I don't know how to check if either one is true. How does one combine two stdout outputs in a conditional check? I have removed the -q
flag from the grep calls with no effect.
Upvotes: 2
Views: 1689
Reputation: 85845
Actually you just use the exit-code
of grep
directly after asking it to run silent -q
if cmd1 | grep -q "check_txt1" || cmd2 | grep -q "check_txt2"
then
echo "Your code here!"
fi
Upvotes: 3
Reputation: 30933
The [[
compound command evaluates a conditional expression, but you just want the result of a pipeline. You need to combine your two pipelines in a list using ||
:
if stout_cmd1 | grep -q 'check_txt1' || stdout_cmd2 | grep -q 'check_txt2'
then
# your code here
fi
From the Bash manual:
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.
#!/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
This produces the following output:
00 contains neither 1 nor 2
01 contains a 1 or 2
02 contains a 1 or 2
12 contains a 1 or 2
Upvotes: 0