On Tue, Apr 21, 2015 at 2:44 PM, Dr Alun J. Carr <alun.j.c...@runbox.com> wrote:
> There appears to be a bug in bash when using a variable in curly brace > expansion, e.g., {1..$n}. I have put the two following test scripts in the > attached files looper1.sh and looper2.sh: > > #looper1.sh > for i in {1..4} > do > echo i = $i > done > > #looper2.sh > n=4 > for i in {1..$n} > do > echo i = $i > done > > Tests were done with bash, ksh, zsh, pdksh, dash and heirloom System V > Bourne sh with the following versions: > bash 3.2.57(1) > bash 4.3.33(1) > ksh version sh (AT&T Research) 93u+ 2012-08-01 > zsh 5.0.5 (x86_64-apple-darwin14.0) > pdksh stable 5.2.14 > dash stable 0.5.8 > sh ??? > > Results for bash (both versions give the same result); note that bash > fails to expand the curly brace expression in only the second case: > > $ bash looper1.sh > i = 1 > i = 2 > i = 3 > i = 4 > > $ bash looper2.sh > i = {1..4} > > Repeating using ksh we get correct expansion of the curly braces: > > $ ksh looper1.sh > i = 1 > i = 2 > i = 3 > i = 4 > > $ ksh looper2.sh > i = 1 > i = 2 > i = 3 > i = 4 > > And using zsh, the same result as for ksh: > > $ zsh looper1.sh > i = 1 > i = 2 > i = 3 > i = 4 > > $ zsh looper2.sh > i = 1 > i = 2 > i = 3 > i = 4 > > Neither pdksh (which installs as ksh using homebrew) nor dash handle > either case correctly: > > pdksh: > > $ /usr/local/bin/ksh looper1.sh > i = {1..4} > > $ /usr/local/bin/ksh looper2.sh > i = {1..4} > > dash: > > $ dash looper1.sh > i = {1..4} > > $ dash looper2.sh > i = {1..4} > > The System V sh from the heirloom project behaves the same way as pdksh > and dash (or more correctly, since System V is really the reference, pdksh > and dash behave the same way as SysV sh): > > $ 5 sh looper1.sh > i = {1..4} > > $ 5 sh looper2.sh > i = {1..4} > > > Bash performs brace expansion before variable expansion and thus does not support the feature that zsh and ksh have which do variable expansion before brace expansion. To use a variable, use C-style for loops: for ((i = 1; i <= 4; i++)) -- Visit serverfault.com to get your system administration questions answered.