Checking if output of a command contains a certain string in a shell script Checking if output of a command contains a certain string in a shell script shell shell

Checking if output of a command contains a certain string in a shell script


Testing $? is an anti-pattern.

if ./somecommand | grep -q 'string'; then  echo "matched"fi


Test the return value of grep:

./somecommand | grep 'string' &> /dev/nullif [ $? == 0 ]; then   echo "matched"fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then   echo "matched"fi

and also:

./somecommand | grep -q 'string' && echo 'matched'


Another option is to check for regular expression match on the command output.

For example:

[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"