Monday, July 20, 2009

Shell gotcha: when comments execute

The problem: a colleague has a script which dies early, something like this (with the -x flag):

+ [ 2 -eq 2 ]
+ break
+ exit

The corresponding shell (KSH, but same results in BASH):

if [ $cond1 -eq $cond2 ]
then
   break
fi

# Lots of commented out code

more commands ...

The curiosity: why the early exit? The logic does not have an exit anywhere nearby; the commands following do not call exit.

Follow Sherlock Holmes' dictum, How often have I said to you that when you have eliminated the impossible, whatever remains, however improbable, must be the truth? (The Sign of the Four) The only thing left is the commented out code.

Sure enough:

# Blah, blah
# Something with $(hidden command) buried inside
# More blahbage

I had completely forgotten that the shell expands variables even inside comments! In this case, the expanded $(hidden command) blew up and caused the shell to exit prematurely. Caveat plicator.

No comments: