0

I am trying to understand why this loop does not print a number for each arguments supplied to the script.

#!/bin/bash

for i in {1..$#}; do
  echo $i
done

Instead, when supplied e.g. 3 arguments, it outputs

{1..3}

2 Answers 2

3

The expression {} does not accept variables.

To do so, you need to work with for example seq. The following will make it::

#!/bin/bash

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

Note that $() is equivalent to ``. That is, it performs a command substitution. For example:

$ d=$(echo "hello")
$ echo $d
hello

You can see more information in Shell Programming: What's the difference between $(command) and command.

Tests

$ ./a
$

$ ./a a b c
1
2
3
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Can you explain what the dollarsign does in this context? I understand the dollarsign as a prefix to refer to variables, but I don't see any assignment in the parentheses.
Thank you. So seq is actually an executable and not a language construct. It makes good sense.
Exactly! You explained it better than me :) See for example $ which seq that returns something like /usr/bin/seq.
1

Brace expansion occurs before variable expansion

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Expansions

Comments

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.