如何使用/ bin/sh检查模式匹配,而不是/ bin/bash

har*_*ryz 16 shell

我正在使用Ubuntu系统shell,而不是bash,我发现常规方式无法正常工作:

#!/bin/sh
string='My string';

if [[ $string =~ .*My.* ]]
then
   echo "It's there!"
fi
Run Code Online (Sandbox Code Playgroud)

错误[[:找不到!

我该怎么做才能解决这个问题?

gav*_*koa 19

为什么使用grep这样简单的模式?通过Sh内置匹配引擎避免不必要的fork:

case "$value" in
  *XXX*)  echo OK ;;
  *) echo fail ;;
esac
Run Code Online (Sandbox Code Playgroud)

它符合POSIX标准.Bash 为此简化了语法:

if [[ "$value" == *XXX* ]]; then :; fi
Run Code Online (Sandbox Code Playgroud)


Chr*_*lan 18

[[ ... ]]是一种打击主义.您可以通过只使用让您的测试壳不可知grep与正常if:

if echo "$string" | grep -q "My"; then
    echo "It's there!"
fi
Run Code Online (Sandbox Code Playgroud)


dev*_*ull 5

你可以使用expr:

if expr "$string" : "My" 1>/dev/null; then
  echo "It's there";
fi
Run Code Online (Sandbox Code Playgroud)

这适用于shbash.

作为一个方便的功能:

exprq() {
  local value

  test "$2" = ":" && value="$3" || value="$2"
  expr "$1" : "$value" 1>/dev/null
}

# Or `exprq "somebody" "body"` if you'd rather ditch the ':'
if exprq "somebody" : "body"; then 
  echo "once told me"
fi
Run Code Online (Sandbox Code Playgroud)

引用自man expr:

   STRING : REGEXP
          anchored pattern match of REGEXP in STRING
Run Code Online (Sandbox Code Playgroud)

  • 如果你**总是想在字符串的开头匹配**,那就太好了,否则它将无法工作(他们到底为什么要加入这个限制?) - 顺便说一句,这个答案不满足OP的具体要求大小写,匹配**字符串中的任何位置**。 (2认同)