0

I am trying to do something like this in shellscript:

STEP=5
LIST=[1-$STEP]

for i in $LIST
    echo $i
done

The output I expect is:

1 2 3 4 5

I probably have seen this usage before ( e.g. [A-Z] ) but I cannot remember the correct syntax. Thank you for your help!

Étienne
  • 4,773
  • 2
  • 33
  • 58
Han Chen
  • 1
  • 1
  • Like this perhaps: http://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-in-bash – minopret Feb 24 '12 at 05:34

2 Answers2

1

Try this. Note that you use the echo command which includes an LF. Use echo -n to get output on the same line as shown

    STEP=5
for i in `seq 1 $STEP`; do

echo $i

done
ABS
  • 2,092
  • 1
  • 13
  • 6
  • Note that `seq` is not a POSIX utility and may not be available. `echo -n` should never be used; use `printf` instead, which can portably supress the newline. – Jens May 22 '13 at 09:32
0

Assuming this is bash:

$ echo {1..5}
1 2 3 4 5
$ STEP=5
$ echo {1..$STEP}
{1..5}
$ eval echo {1..$STEP}
1 2 3 4 5
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • 1
    This is great until you run it in a directory where there's a file named "1" because some bonehead typo'd a redirect. Then the {1..5} expands to "1" and you spend *hours* trying to diagnose the problem. :) Unless you use noglob because you've done this before and never want to have that problem again. – dannysauer Apr 08 '12 at 03:16
  • @dannysauer Brace expansion is not file name globbing. `echo {1..5}` outputs `1 2 3 4 5` whether or not a file named `1` is present. Are you confusing this with `echo [1-5]`? – Jens May 22 '13 at 09:28
  • @dannysauer, verify for yourself: the bash sequence of expansions is documented: http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions – glenn jackman May 22 '13 at 14:41
  • I was probably thinking of a time when I was attempting to do a string comparison using a wildcard (think "{1,2,3}*") and the shell expanded the wildcard to the matching filename rather than preserving the wildcard, screwing up the comparison. Or maybe I was thinking of a variable containing an array index with the brackets, or some other random thing. – dannysauer May 22 '13 at 20:39
  • To save face, I still maintain that it's a good idea to turn on noglob in shell scripts - only explicitly disabling it when glob-based word expansion is desired. ;) – dannysauer May 22 '13 at 20:41