0

I have a bash array as follows:

fruits=(
F001 "Sour fruit" 5
F002 "Sweet fruit" 15
F003 "Good fruit" 10
)

I want to access this array and print it as follows:

Fruit code: F001, Desc: Sour fruit, Price: 5
Fruit code: F002, Desc: Sweet fruit, Price: 15
Fruit code: F003, Desc: Good fruit, Price: 10

I tried the following code, But it's giving me a wrong output

for f in "${fruits[@]}"; do
    IFS=" " read -r -a arr <<<"${f}"

       code="${arr[0]}"
       desc="${arr[1]}"
       price="${arr[2]}"
       echo "Fruit code: : ${code}, Desc: ${desc}, Price: ${price}"
       echo
done

Anyine know how to do this :)

3
  • 1
    What output is it giving you? how does it differ from what you expect? Commented Apr 26, 2022 at 10:52
  • 1
    bash arrays can not contain nested arrays as elements. It's not clear to me what you want to achieve. Commented Apr 26, 2022 at 11:14
  • 1
    run typeset -p fruits (or declare -p fruits) to see what's really in your array; as kvantour has noted ... you should see 9 items in the array, not the 3 you're expecting Commented Apr 26, 2022 at 14:00

1 Answer 1

3

The bash array you define does not have 3 elements, but 9. So you can quickly do this with a modulo 3 operation:

for ((i=0;i<"${#fruits[@]}";i=i+3)); do
  code="${fruits[i]}"
  desc="${fruits[i+1]}"
  price="${fruits[i+2]}"
  echo "Fruit code: : ${code}, Desc: ${desc}, Price: ${price}"
done
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.