0

I currently encountered a tricky problem on which I couldn't find any solution yet.

I wrote a script like this:

#!/bin/sh 
x=1
while [ "$x" -le $# ]; do
echo "$x"'. Argument is: ' "\$$x"
x="$(( $x + 1 ))"
done

I suggested that the shell would evaluate the expression "\$$x" after expanding the variables to get access to the argument on position x but the output is:

1. Argument is: $1

Please help. Thx in advance.

IlikePepsi
  • 645
  • 1
  • 8
  • 18

2 Answers2

2

Here is the fix

$ cat a.sh
#!/bin/sh

x=1
while [ "$x" -le $# ]; do
echo "$x"'. Argument is: ' "${!x}"    # If you need indirect expansion, use ${!var} is easier way.
x="$(( $x + 1 ))"
done

Test result

$ sh a.sh a b c
1. Argument is:  a
2. Argument is:  b
3. Argument is:  c
BMW
  • 42,880
  • 12
  • 99
  • 116
  • Thank you for the answer. The fix works on bash but I still got a problem since I'm writing the script on my DD-Wrt router which comes with busybox v1.22.0 and an 'ash' implementation that puts out the following: `syntax error: bad substitution` – IlikePepsi Feb 07 '14 at 19:20
0

This code should work:

#!/bin/sh
x=0
args=($@)
while [ "$x" -lt $# ]; do
    echo "$x"'. Argument is: ' "${args[${x}]}"
    x="$(( $x + 1 ))"
done
drolando
  • 507
  • 2
  • 7