2

I want to refer to a parameter in bash by using a number generated by a sum. How do I do this?

More specifically:

    #!/bin/bash

    $sum=${$1}
    echo $sum

When I execute the script ./script.bash A B C D, if $sum = 3, then I want to return C. How do I do this, does anyone know?

1 Answer 1

6

You can use the indirect expansion syntax:

${!parameter}

as described here.

(Also note that variable assignments should not have a $ on the left-hand side!)

Example:

$ cat script.bash 
#!/bin/bash

sum=3
arg=${!sum}
echo $arg
$ ./script.bash A B C D
C
$
Sign up to request clarification or add additional context in comments.

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.