0

The following bash script works fine to print numbers from 1 to 10:

for i in {1..10}
do
  echo "$i"
done

But if I want to make the upper limit a variable, then this script does not works.

i=10
for j in {1..$i}
do
  echo "$j"
done

Can anyone suggest please how to make the second script work?

0

2 Answers 2

1

Brace expansion happens before any other expansion.

You can say:

for j in $(seq 1 $i); do echo "$j"; done

Quoting from the link above:

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. To avoid conflicts with parameter expansion, the string ‘${’ is not considered eligible for brace expansion.

Sign up to request clarification or add additional context in comments.

4 Comments

Just wondering about history of seq command since I could never use it on my Mac.
@anubhava I'm not sure which OSX version you're using, but I've found it to exist on any variant that I've used, 10.8.x or 10.5.x or whatever ...
@anubhava Maybe you did sudo rm -f $(which seq) and have forgotten doing so!
lol :) I must be really insane to remove a system binary, Why would anyone do that?
1

You cannot use variables in {..} directive of Bash. Use BASH arithmetic operator ((...)) like this:

i=10
for ((j=1; j<=i; j++)); do
    echo "$j"
done

2 Comments

a space would be needed here between for and bracket? Thanks for the reply.
@prabhat: As you can space is already there after for but for me it worked with or without space.

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.