1

I want to access an argument from when the script was run, and I want to get the specific argument based on the variable. So I want to get the argument $2 but rather than typing two, I use the variable that contains a number

Something like this

FOO=2 echo $FOO

The problem is both variables and arguments both use $ so I don't know how to call an specific argument based on the number in the variable. I know I'm explaining this terribly, correct me if you can.

1 Answer 1

2

bash allows indirection with the ${!name} notation, where name is the name of a variable whose value is the name of the variable you want to access. So, in your example you could print the second positional parameter like

foo=2
printf '%s\n' "${!foo}"

or

printf 'The value at %s is %s\n' "$foo" "${!foo}"

which will print something like

The value at 2 is secondParameterValue

Some good reading on indirection can be found here

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.