diff --git a/Sc2086.md b/Sc2086.md new file mode 100644 index 0000000..15abd29 --- /dev/null +++ b/Sc2086.md @@ -0,0 +1,26 @@ +#Double quote to prevent globbing and word splitting. + +### Problematic code: + echo $1 + +### Correct code: + echo "$1" + +### Rationale +The problematic code looks like "print the first argument". It's actually "Split the first argument by spaces, tabs and line feeds. Expand each of them as if it was a glob. Join all the resulting strings and filenames with spaces. Print the result." + +Quoting prevents word splitting and glob expansion, and prevents the script from breaking when input contains spaces, line feeds, glob characters and such. + +### Contraindications +Sometimes you want to split on spaces, like when building a command line. + + options="-j 5 -B" + make $options file + +Just quoting this doesn't work. Instead, you should have used an array: + + options=(-j 5 -B) + make "${options[@]}" file + +To split on spaces but not perform glob expansion, Bash has a `set -f` to disable globbing. +