Niels B.
Niels B.

Reputation: 6310

Using $# in bash loops

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}

Upvotes: 0

Views: 373

Answers (2)

glenn jackman
glenn jackman

Reputation: 246807

Brace expansion occurs before variable expansion

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

Upvotes: 1

fedorqui
fedorqui

Reputation: 289725

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

Upvotes: 3

Related Questions