Sunday, September 28, 2014

$? is a very fragile thing

#!/bin/sh

foo() { return 42; }

while ! foo; do
    if [ $? -eq 42 ]; then
        echo "foo() has indeed returned 42"
        # This should exit with a status of 42, right?
        exit $?
    fi
done
It should've dawned on me that there's a glaring bug in there: the return status of the echo command will overwrite the value of $?.

It took me some more time to realize that there are two bugs in there: ! is also a command, and its return status will also overwrite $?.

It took me much longer to realize that there are three bugs in there: [ is also a command, and yadda yadda yadda.

God I get tired of this shit sometimes...

No comments: