DEV Community

Cover image for Here's Why You Should Quote Your Variables in Bash

Here's Why You Should Quote Your Variables in Bash

Nick Janetakis on October 16, 2018

This article was originally posted on October 2nd 2018 at: https://nickjanetakis.com/blog/here-is-why-you-should-quote-your-variables-in-bash W...
Collapse
 
illandan profile image
Illandan Konduras • Edited

You may already know this - I quote this here since I don't see any reference to Bash' set builtin options in your article. From the Bash manual:

-u

Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion. If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status. 

In other words, you can use set -u to treat unset variables as an error and set -x to bail out of the script if any command returns a non-zero exit status. Here's the link to bash man page.

Thanks and have fun!

EDIT: Oh, since you were talking about shell expansion via globs, you may also want to know about disabling shell/path expansion in bash scripts. There's set -f or set -o noglob for that. This is all just to avoid problems with shell globbing, you may as well quote your variables, just as you should eat your vegetables for nutrition. :D

Collapse
 
nickjj profile image
Nick Janetakis • Edited

Cool thanks. I actually didn't know about -u.

What I typically do is use the shellcheck tool to lint my scripts, and it'll warn you that all hell may break loose if you forget your quotes.

There is also a VSCode extension for it at: github.com/timonwong/vscode-shellc...

Collapse
 
vguarnaccia profile image
Vincent Guarnaccia

This reminds me of a post about malicious code execution via wild cards. I particularly like the tar example.

Collapse
 
benjaminblack profile image
Benjamin Black

Too many people have ingrained rm -rf into muscle memory. It even has a mnemonic, "rimraf." Drop the -f and add -i, for your own safety. Then, only use -f explicitly, and never by default.

Collapse
 
david_j_eddy profile image
David J Eddy

Thank you for this. To many times have I scratched my head wondering how BASHes variable and quotes worked. Now I know :D.