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

user1118764 picture user1118764 · Jun 5, 2013 · Viewed 164.3k times · Source

I'm writing a shell script, and I'm trying to check if the output of a command contains a certain string. I'm thinking I probably have to use grep, but I'm not sure how. Does anyone know?

Answer

mat picture mat · Jul 3, 2015

Testing $? is an anti-pattern

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