如何在/bin/sh脚本中编写和匹配正则表达式?

How to write and match regular expressions in /bin/sh script?

我正在为没有 bash 的基于 unix 的有限微内核编写 shell 脚本!由于某些原因,/bin/sh 不能 运行 以下行。

if [[ `uname` =~ (QNX|qnx) ]]; then
read -p "what is the dev prefix to use? " dev_prefix
if [[ $dev_prefix =~ ^[a-z0-9_-]+@[a-z0-9_-"."]+:.*$ ]]; then

对于第 1 行和第 3 行,它抱怨缺少表达式运算符,对于第 2 行,它说没有协处理!谁能阐明 /bin/bash 和 /bin/sh 脚本之间的区别?

您可以在 /bin/sh 中使用此等效脚本:

if uname | grep -Eq '(QNX|qnx)'; then
   printf "what is the dev prefix to use? "
   read dev_prefix
   if echo "$dev_prefix" | grep -Eq '^[a-z0-9_-]+@[a-z0-9_-"."]+:'; then
   ...
   fi
fi

您可以使用 shellcheck 检测脚本中的非 Posix 功能:

Copy/Paste这个变成https://www.shellcheck.net/:

#!/bin/sh
if [[ `1uname` =~ (QNX|qnx) ]]; then
  read -p "what is the dev prefix to use? " dev_prefix
  if [[ $dev_prefix =~ ^[a-z0-9_-]+@[a-z0-9_-"."]+:.*$ ]]; then
    : nothing
  fi
fi

或者在本地安装shellcheck,并且运行 shellcheck ./check.sh, 它将突出显示非 posix 功能:

In ./check.sh line 2:
if [[ `1uname` =~ (QNX|qnx) ]]; then
   ^-- SC2039: In POSIX sh, [[ ]] is not supported.
      ^-- SC2006: Use $(..) instead of deprecated `..`

In ./check.sh line 4:
  if [[ $dev_prefix =~ ^[a-z0-9_-]+@[a-z0-9_-"."]+:.*$ ]]; then
     ^-- SC2039: In POSIX sh, [[ ]] is not supported.

您要么必须将表达式重写为 glob(不现实),要么使用外部命令 (grep/awk),@anubhava

对此进行了解释