0

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 Answer 1

3

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

2 Comments

Awesome! As i am reading this from a csv, would it be possible to convert my existing array to an associative array? This way i can keep my csv a bit cleaner so to speak
@volc: Feel free to ask a new question.

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.