ACs
ACs

Reputation: 1445

Perform a grep in an if

How could I perform a grep in an if statement? I'd like to check if a string contains a sub-string.

DSU_DIFF="$(sudo php app/console d:s:u --dump-sql)"
# I want to check if the $DSU_DIFF contains the sub-string "Nothing to update"
if [ "$DSU_DIFF" | grep "Nothing to update" ]
   then
       echo "Contains substring"
else
   echo "No substring contained"
fi

This is syntactically wrong, how should I try this?

Upvotes: 0

Views: 62

Answers (2)

kopiro
kopiro

Reputation: 709

@melpomene is right, but just in case:

if echo "$DSU_DIFF" | grep "Nothing to update"; then
    echo "Contains substring"
else
   echo "No substring contained"
fi

Upvotes: 1

melpomene
melpomene

Reputation: 85767

Why use grep for that?

You can use case:

case "$DSU_DIFF" in
    *'Nothing to update'*)
        echo "Contains substring";;
    *)
        echo "No substring contained";;
esac

Upvotes: 1

Related Questions