Syntax error near =~ operator

心已入冬 提交于 2019-12-24 16:56:13

问题


When I run this script:

#!/bin/bash

if [[ "abcd" =~ ^.*$ ]]; then
    echo "something"
fi

I get:

./tmp2.sh: line 3: conditional binary operator expected
./tmp2.sh: line 3: syntax error near `=~'
./tmp2.sh: line 3: `if [[ "abcd" =~ ^.*$ ]]; then'

I've tried all suggestions I've found, but still the same:/ Help me, please!


回答1:


Given that you're seeing a bash-specific error message, we can rule out that something other than bash is running the script (if it were a POSIX-features-only shell, such as sh on some systems, you'd instead see an error message relating to [[).

The most likely explanation:

  • Your bash version is < 3.0, and therefore doesn't support the =~ operator.
    • To verify, run echo $BASH_VERSION in your script.

The specific error you're seeing is bash's way of saying: "I'm seeing a string I don't recognize as an operator."




回答2:


Run your script with bash script.sh not sh script.sh. It probably would also work with ./script.sh if script.sh is already executable since you're using the header #!/bin/bash.




回答3:


this should work

re='^.*$'
if [[ "abcd" =~ $re ]]; then
  echo "something"
fi


来源:https://stackoverflow.com/questions/24713891/syntax-error-near-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!