字符串包含在Bash中
我在Bash中有一个字符串:
string="My string"
我如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
  echo "It's there!"
fi
  哪里??  是我未知的运营商。  我使用echo和grep ? 
if echo "$string" | grep 'foo'; then
  echo "It's there!"
fi
这看起来有点笨拙。
如果使用双括号,你也可以在case语句之外使用Marcus的答案(*通配符):
string='My long string'
if [[ $string = *"My long"* ]]; then
  echo "It's there!"
fi
  请注意,针串中的空格需要放在双引号之间,并且*通配符应位于外部。 
如果你喜欢正则表达式的方法:
string='My string';
if [[ $string =~ .*My.* ]]
then
   echo "It's there!"
fi
我不确定使用if语句,但是您可以通过case语句获得类似的效果:
case "$string" in 
  *foo*)
    # Do stuff
    ;;
esac
