January 19, 2021•192 words
Today I will talk about unexpected control flow in shell
I was doing code review of a piece of shell code. It looked good on paper, if some poor soul is printing shell on paper, and was even shellcheck-clean, but we decided to add
set -e at the top of the script, to see if anything was failing silently.
It was, obviously.
After a moment of shock and disbelief, it struck us what was broken. The broken part was inside out heads. Shell itself did exactly what we told it to do. Our understanding of the semantics of all the shell features, combined, was the faulty element.
The code we looked at can be reduced to this snippet:
set -e a=0 ((a++)) # surprise, exit 1 here
If you don't immediately see the problem and are unwilling to look at the
bash(1) manual page for clues, let me just jump to the conclusion.
shellcheck warn about this issue? It might. I doubt any developer intentionally wrote code with the desire to always exit after the assignment, just because
set -e and
((a++)) together require that.