4

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

1
  • 1
    Try IFS=0; echo $?
    – mikeserv
    Dec 23, 2014 at 5:28

2 Answers 2

5

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .