I bet you’ve seen a lot of scripts with seemingly innocent
if [ -e blah ];then ...; else ...; fi or something similar . What’s the problem?
if has at most two branches while
[[ have three different exit codes. Oops.
If you make a syntax error (or any other error occurs) in the
[[ expression, it will return the exit code 2 (or above, according to
if will take the
else branch. If you are lucky, you will notice the error message from the
[[ commands. If not, the
else branch will always be executed.
I don’t want to use bash. The pitfall above is one of the many reasons. Unfortunately, I do use bash because it’s still best tool for some tasks. I’m working on alternative to bash. It’s called NGS, the Next Generation Shell. In NGS, the situation above is solved as one would expect from a modern programming language: exit codes 2 and above throw exception.
If you also think that there should be a viable alternative to bash, you are welcome to help me working on it.
Update 2021-12-31: real world example is at https://github.com/awslabs/aws-lambda-cpp/issues/140
Happy coding! Hope it’s not in bash 🙂
2 thoughts on “Bash pitfall: if test, if [, if [[”
whats wrong using python (for multi platform )
Nothing. You can also use many other general purpose languages. You will not have the level of convenience for typical Ops tasks: running external programs, pipes, redirects, capturing output, etc (as opposed to bash or NGS)