mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created Sc2086 (markdown)
26
Sc2086.md
Normal file
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.
|
||||||
|
|
Reference in New Issue
Block a user