From 44dbb5648b4a0bdf38a5161ca54173cfec6efeb5 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sat, 31 Dec 2016 13:44:01 -0800 Subject: [PATCH] Created SC2200 (markdown) --- SC2200.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SC2200.md diff --git a/SC2200.md b/SC2200.md new file mode 100644 index 0000000..81a14e1 --- /dev/null +++ b/SC2200.md @@ -0,0 +1,29 @@ +## Brace expansions don't work as operands in [ ]. Use a loop. + +### Problematic code: + +```sh +[ "$file" = index.{htm,html,php} ] && echo "This is the main file" + +``` + +### Correct code: + +```sh +for main in index.{htm,html,php} +do + [ "$file" = "$main" ] && echo "This is the main file" +done +``` + +### Rationale: + +Brace expansions in `[ ]` will expand to a sequence of words. Operators work on single words. + +The problematic code is equivalent to `[ "$file" = index.htm index.html index.php ]`, which is invalid syntax. A typical error message is `bash: [: too many arguments` or `dash: somefile: unexpected operator`. + +Instead, use a `for` loop to iterate over values, and apply your condition to each. + +### Exceptions: + +None. \ No newline at end of file