Bash select from array by argument

707 views Asked by At

I have an array filled with elements like these;

vars=($bla=123 foo=456 bar=789)

Now, i can use these and split them with IFS '=' like this:

for var in "${vars[@]}"; do
    IFS='=' read -a split <<< ${vars}
    nr=${split[1]}
    title=${split[0]}

Which works perfectly.

However, i want to be able to select for instance item foo=456 by passing an argument to the script like 'foo'. 'foo' would be $2. Is this possible in bash?

I was thinking in this direction :

"${vars[@]$2}"
1

There are 1 answers

2
choroba On BEST ANSWER

Use associative array (needs bash 4+):

#!/bin/bash
bla=xyz
declare -A vars=([$bla]=123 [foo]=456 [bar]=789)

set -- one foo
echo ${vars[$2]}