Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

bash

shell

People also ask

How do you grep from a command output?

Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. 6. Show line number while displaying the output using grep -n : To show the line number of file with the line matched.

How do I test a string in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.


Testing $? is an anti-pattern.

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

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 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'"

A clean if/else conditional shell script:

if ./somecommand | grep -q 'some_string'; then
  echo "exists"
else
  echo "doesn't exist"
fi

This looks more obvious, doesn't it?

# Just a comment... Check if output of command is hahaha
MY_COMMAND_OUTPUT="$(echo hahaha)"
if [[ "$MY_COMMAND_OUTPUT" != "hahaha" ]]; then
  echo "The command output is not hahaha"
  exit 2
else
  echo "The command output is hahaha"
fi