在if中执行grep

时间:2018-11-16 16:27:49

标签: shell

如何在if语句中执行grep?我想检查字符串是否包含子字符串。

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

这在语法上是错误的,我应该如何尝试呢?

2 个答案:

答案 0 :(得分:1)

为什么要为此使用case

您可以使用case "$DSU_DIFF" in *'Nothing to update'*) echo "Contains substring";; *) echo "No substring contained";; esac

42ND-1000 
W61ST-1000 
TIFF-1000 
THIR-1000 

答案 1 :(得分:1)

@melpomene是正确的,但以防万一:

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