Updated SC2051 (markdown)

koalaman
2014-09-09 16:54:09 -07:00
parent 9fecdfb38d
commit 1cd6f2ff52

@@ -1,25 +1,37 @@
## Bash doesn't support variables in brace range expansions. ## Bash doesn't support variables in brace range expansions.
### Problematic code: ### Problematic code:
for i in {1..$n} for i in {1..$n}
do do
echo "$i" echo "$i"
done done
### Correct code: ### Correct code:
for ((i=0; i<n; i++)) for ((i=0; i<n; i++))
do do
echo "$i" echo "$i"
done done
### Rationale: ### Rationale:
In Bash, brace expansion happens before variable expansion. This means that brace expansion will not account for variables. In Bash, brace expansion happens before variable expansion. This means that brace expansion will not account for variables.
Use an arithmetic for loop instead. For integers, use an arithmetic for loop instead. For zero-padded numbers or letters, use of eval may be warranted:
### Contraindications from="a" to="m"
for c in $(eval "echo {$from..$to}"); do echo "$c"; done
or more carefully (if `from`/`to` could be user input, or if the brace expansion could have spaces or globs):
from="a" to="m"
while IFS= read -d '' -r c
do
echo "Read $c"
done < <(eval "printf '%s\0' $(printf "{%q..%q}.jpg" "$from" "$to")")
### Contraindications
None (if you're writing for e.g. zsh, make sure the shebang indicates this so shellcheck won't warn) None (if you're writing for e.g. zsh, make sure the shebang indicates this so shellcheck won't warn)