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

时间:2014-01-14 13:47:07

标签: shell

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

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

if [[ $string =~ .*My.* ]]
then
   echo "It's there!"
fi

错误[[:找不到!

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

4 个答案:

答案 0 :(得分:18)

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

case "$value" in
  *XXX*)  echo OK ;;
  *) echo fail ;;
esac

符合POSIX标准。 Bash对此有simplified syntax

if [[ "$value" == *XXX* ]]; then :; fi

答案 1 :(得分:17)

[[ ... ]]是bash-ism。只需使用grep if,就可以使测试与shell无关:

if echo "$string" | grep -q "My"; then
    echo "It's there!"
fi

答案 2 :(得分:5)

您可以使用expr

if expr "$string" : "My" 1>/dev/null; then
  echo "It's there";
fi

这适用于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

引自man expr

   STRING : REGEXP
          anchored pattern match of REGEXP in STRING

答案 3 :(得分:0)

[ "${string#*My}" != "$string" ] && echo "It's there!"

${...}

${...}语法执行变量扩展;这种形式的多种形式都是可移植的(包括有用的${foo#bar}${foo##bar}${foo%bar}${foo%%bar},但有一些不是。

${!...}执行间接变量扩展,这是一种基础;改为使用eval。

${parameter/pattern/string}执行模式替换,这是一种基础。有关解决此问题的建议,请参阅下一节。

${parameter:offset:length}执行子串扩展,这是一种基础。请参阅以下有关解决此问题的建议。

数组变量不可移植。在关注合适的分离器时,通常可以用一系列${foo#bar}扩展替换它们,而不会显着影响性能。