0

I shell scripts I see compares always written this way:

if [ "$?" -eq 0 ]
then ...

What the purpose of the double-quotes around the variable?

If I remove the quotes then it doesn't seem to have an effect. Is it for preventing something?

  • 1
    And there's a comprehensive post on Unix & Linux about the security aspect of quoting. – muru Jul 30 '18 at 7:26
  • In this case, $? always returs a number which signifies exit status of previous command(s). So quoting or not quoting is irrelevant for this one, but quoting exists to avoid word splitting, aka treating items separately. With variable v='hello world' , when you use bare $v shell will treat its expansion as two elements hello and world, with quotes - "$v" is treated as single unit. Read the linked posts, it's explained much more in-depth there. – Sergiy Kolodyazhnyy Jul 30 '18 at 8:20
  • Also don't be confused by the "word" in word splitting, has nothing to do with text. It applies just as equally to v='1234 5678' – Sergiy Kolodyazhnyy Jul 30 '18 at 8:22
  • @Sergiy Kolodyazhnyy Thanks a lot. :) The quotes make now sense to me. – mizech Jul 30 '18 at 8:29

Browse other questions tagged or ask your own question.