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!

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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

5 Comments

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 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]?
@dannysauer, verify for yourself: the bash sequence of expansions is documented: gnu.org/software/bash/manual/bashref.html#Shell-Expansions
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.
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. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.