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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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
Won;t work in bash shell.
0

This code should work:

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

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.