I want to use the “conditional regexp” structure from bash, present since the third version of bash (circa 2004).
It’s supposed to go like this:
if [[ $string =~ $regexp ]]; then
#do smthg
else
#do somthg else
fi
So here’s my code, following this structure, and its role is to check if the name contained in SSID is presend in the output from iw dev wlan0 link :
if [[ $(iw dev wlan0 link) =~ $SSID+ ]]; then
#do sthming
else
echo "wrong network"
fi
For some reason that i can’t decipher, this statement works pretty well if I run it right into the bash shell, like
if [[ $(iw dev wlan0 link) =~ $SSID+ ]]; then echo found; else echo not found; fi
But if i run it inside the script its contained, it’ll spit out:
scripts/ssidchecker.sh: 22: [[: not found
22 being the line of the “fi” keyword. The strangest thing is that it will always execute the code contained in the “else” statement
Is “not found” meant to indicate me that the regexp dind’t find anything in that string? Is it a real error message?
Starting Note: Answer created with input from comments in question, especially in response of the last comment.
First, what is
[[? It is a shell keyword.This means that
[[is an internal keyword of bash, not a command and thus will not work with other shells. Thus, your error outputmeans that the shell you’re using is probably
[[introduced in Bash-2.02)Given that 2.02 is a really really old version (pre Y2K), all this just points to the fact that the shell you’re using to run the script is probably not
/bin/bash, instead probably being/bin/shwhich is the most common path used for Bourne shell scriptsshebang(the#!) line.Please change that to
/bin/bashor explicitly runbash scripts/ssidchecker.shand you’re good to go.As to why the
elsesection was always executed, the[[command not being found is the same as a failure (non-zero return value), from the viewpoint ofif. Thus theelsesection is executed.As a side note on portability, the bash hackers wiki also says the following about the
[[keyword:Thus your script will probably fail on the
=~even if the shell supports[[, in case the shell isn’tbashbut supports[[.