A bad mix of bash and sh with [[

If you accidentally run a bash script with sh, you’re probably going to have a bad time.

One little gotcha is the use of [[ (double square brackets) in bash.

E.g.:

if [[ -z "${PROJECT_ID}" ]]; then
    echo 'PROJECT_ID is empty, exiting'
    exit 1
fi

Bash will check the condition as expected. Sh, on the other hand, will reject the double-brackets syntax that it is not aware of with a message like this:

[[: not found

That wouldn’t be so bad, but by default it will then continue running the script.

If you were using the condition for a validation check as in the example above, this can be pretty disastrous: the script would carry on with invalid input, which is what the check was supposed to prevent.

Sh will ignore a shebang line like #!/usr/bin/env bash at the start of the script, so you have to make sure the script is being run with the shell you’re expecting.


View post: A bad mix of bash and sh with [[