Reputation: 675
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.
Upvotes: 0
Views: 2933
Reputation: 45293
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
Upvotes: 2
Reputation: 507
This code should work:
#!/bin/sh
x=0
args=($@)
while [ "$x" -lt $# ]; do
echo "$x"'. Argument is: ' "${args[${x}]}"
x="$(( $x + 1 ))"
done
Upvotes: 0