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...
For further actions, you may consider blocking this person and/or reporting abuse
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:In other words, you can use
set -u
to treat unset variables as an error andset -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
orset -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. :DCool 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...
This reminds me of a post about malicious code execution via wild cards. I particularly like the
tar
example.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.Thank you for this. To many times have I scratched my head wondering how BASHes variable and quotes worked. Now I know :D.