2

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 "$@")?

  • Try IFS=0; echo $? – mikeserv Dec 23 '14 at 5:28
4

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
  • 1
    Ahhh IFS, I see. Thanks. That other answer you linked is fantastic too. – Daniel Dec 23 '14 at 7:10
  • Long story, short: if it is a variable in shell, you should probably always quote it. – HalosGhost Dec 23 '14 at 12:41
2

Technically, you don't need to quote the left-hand side within [[ ... ]]. But as Stéphane Chazelas put it in comments on his beautiful answer, there's no compelling reason not to quote it, so just do it and sleep better at night. It's a good recommended practice, less doubts and questions asked.

In old-style [ ... ] you must quote, you don't have a choice. In any case you shouldn't use old-style [ ... ] anymore, the new style [[ ... ]] is the recommended way.

  • 1
    Thanks also janos, that answer by Stéphane is a great read. – Daniel Dec 23 '14 at 7:12
  • Thanks, I don't agree one should prefer [[...]] over [...] though. See also there – Stéphane Chazelas Jan 21 '15 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.