Home > other >  Print bash array of arrays to certain format
Print bash array of arrays to certain format

Time:04-27

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 :)

CodePudding user response:

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
  • Related