Bash – reason to quote the exit status $? variable

bashquotingshell

I was looking at Google's style guides for their bash scripts, and saw that they quote the exit status variable $? here.

if [[ "$?" -ne 0 ]]; then
    error_message
fi

I thought return values are always numeric, so is there any reason to ever quote them?

Is it just a good habit to get into (because you want to quote other special shell variables like "$@")?

Best Answer

Highly recommend

You should read this wonderful answer for more details.


Setting IFS contains digit can break your code:

$ IFS=0
$ echo test
$ [ $? -eq 0 ] && echo done
bash: [: : integer expression expected

Some shells may inherit IFS from environment (dash, ash), some don't (bash, zsh, ksh). But someone can control the environment, your script will break anyway ($#, $! are also affected).

A note, in your example, you used new test [[...]], so field splitting is turned off, you don't need to quote in this case. It will be matter if you use old test [...].

$ IFS=0
$ echo test
$ [[ $? -eq 0 ]] && echo done
done