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}
Niels B.
  • 5,912
  • 3
  • 24
  • 44

2 Answers2

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 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. – Niels B. Sep 24 '13 at 11:00
  • Thank you. So seq is actually an executable and not a language construct. It makes good sense. – Niels B. Sep 24 '13 at 11:07
  • Exactly! You explained it better than me :) See for example `$ which seq` that returns something like `/usr/bin/seq`. – fedorqui Sep 24 '13 at 11:13
1

Brace expansion occurs before variable expansion

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352