问题
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.
- To verify, run
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