From a7e76c99cd4a3ab735d497895e32c58674665899 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 19 Jul 2015 11:45:15 -0700 Subject: [PATCH] Created SC2165 (markdown) --- SC2165.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 SC2165.md diff --git a/SC2165.md b/SC2165.md new file mode 100644 index 0000000..855d455 --- /dev/null +++ b/SC2165.md @@ -0,0 +1,35 @@ +## This nested loop overrides the index variable of its parent. + +And companion warning "This parent loop has its index variable overridden." + +### Problematic code: + + for((i=0; i<10; i++)) + do + for i in * + do + echo "$i" + done + done + +### Correct code: + + for((i=0; i<10; i++)) + do + for j in * + do + echo "$j" + done + done + +### Rationale: + +When nesting loops, especially arithmetic for loops, using the same loop variable can cause unexpected results. + +In the problematic code, `i` will contain the last filename from the inner loop, which will be interpreted as a value in the next iteration out the outer loop. This results in either an infinite loop or a syntax error, depending on whether the last filename is a valid shell variable name. + +In nested for-in loops, variable merely shadow each other and won't cause infinite loops or syntax errors, but reusing the variable name is rarely intentional. + +### Exceptions: + +None. \ No newline at end of file