bash脚本条件检查语句抛出错误

时间:2016-05-17 14:42:26

标签: bash shell

您好我在下面的这一行收到错误

  BOOTPROTO="dhcp"
  TEST=$([[ "$BOOTPROTO" =~ (static|none|bootp|dhcp)$ ]] ; echo $?)

错误我得到的是

 -bash: command substitution: line 1: unexpected argument `(' to conditional   binary operator
 -bash: command substitution: line 1: syntax error near `(s'
 -bash: command substitution: line 1: `[[ "$BOOTPROTO" =~ (static|none|bootp|dhcp)$ ]] ; echo $?'

我试图手动运行但无法解决它

2 个答案:

答案 0 :(得分:3)

用报价包裹你的正则表达式:

  BOOTPROTO="dhcp"
  TEST=$([[ "$BOOTPROTO" =~ "(static|none|bootp|dhcp)$" ]] ; echo $?)
  echo "$TEST"

或者如果您使用Bash> = 3.2,则转义括号(正如Eric在评论中提到的那样。)

TEST=$([[ "$BOOTPROTO" =~ \(static|none|bootp|dhcp\)$ ]] ; echo $?)

<强>输出

1

答案 1 :(得分:0)

为什么不简单

[[ "$BOOTPROTO" =~ (static|none|bootp|dhcp)$ ]]
TEST=$?