首页 > 解决方案 > 在 if 中执行 grep

问题描述

如何在 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

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

标签: shell

解决方案


为什么要使用grep它?

您可以使用case

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

推荐阅读