Search code examples
arraysbashselectelementifs

Bash select from array by argument


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}"

Solution

  • 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]}