Skip to main content
2 of 11
edited tags
Gilles 'SO- stop being evil'
  • 865.3k
  • 205
  • 1.8k
  • 2.3k

Security implications of forgetting to quote a variable in bash/POSIX shells

If you've been following unix.stackexchange.com for a while, you should hopefully know by now that leaving a variable unquoted in list context (as in echo $var) in Bourne/POSIX shells (zsh being the exception) has a very special meaning and shouldn't be done unless you have a very good reason to.

It's discussed at length in a number of Q&A here (Examples: When is double-quoting necessary?, Expansion of a shell variable and effect of glob and split on it, Quoted vs unquoted string expansion...)

That has been the case since the initial release of the Bourne shell in the late 70s and hasn't been changed by the Korn shell (one of David Korn's biggest regrets) or bash which mostly copied the Korn shell, and that's how that has been specified by POSIX/Unix.

Now, we're still seeing a number of answers here and even occasionally publicly released shell code where variables are not quoted. You'd have thought people would have learnt by now.

In my experience, there are mainly 3 types of people who omit to quote their variables:

  • beginners. Those can be excused as admittedly it's a completely unintuitive syntax. And it's our role on this site to educate them.

  • forgetful people.

  • people who are not convinced even after repeated hammering, who think that surely the Bourne shell author did not intend us to quote all our variables.

Maybe we can convince them if we expose the risk associated with this kind of behaviours.

What's the worse thing than can possible happen if you forget to quote your variables. Is it really that bad?

What kind of vulnerability are we talking of here?

In what contexts can it be a problem?

Stéphane Chazelas
  • 584.6k
  • 96
  • 1.1k
  • 1.7k