Created Sc2086 (markdown)

koalaman
2013-11-10 12:16:41 -08:00
parent ea99b9cf28
commit ed11c74109

26
Sc2086.md Normal file

@@ -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.