0

I am pretty new to bash scripting and just gather all the information I needed for my script.

I want to iterate through an array with a variable name. My script so far:

#!/bin/bash declare -a bff=("Abnehmen" "Buecher" "Dating" "Dating" "Fitness" "Handy" "Hunde" "Reisen" "Schmuck" "Schwanger" "Uhren") declare -a dab=("baby" "beauty" "fitness" "haushalt" "heimwekren") for product in bff dab; do echo "${product[@]}" #works fine, it echoes 'bff' in the first loop for sub in ${!product[@]}; do echo "${product}/${sub}" #does not work, echoes 'bff/0' done done 

Output:

bff bff/0 dab dab/0 ddb ddb/0 dwb dwb/0 pod pod/0 

I don't udnerstand why I can echo the variable correctly, but can't use it in the for loop. The tutorial I've found were only about echoing the varibale variable, but now how to use it in a loop.

Could anyone assist me here or guide me in the correct direction?

My desired output would be:

bff bff/Abnehmen bff/Buecher bff/Dating ... dab dab/baby dab/beauty ... 
2
  • Do you really need something this complex? Have you considered echo bff; printf 'bff/%s\n' ${bff[@]}; echo dab; printf 'dab/%s\n' ${dab[@]};?
    – terdon
    CommentedMar 13, 2020 at 13:06
  • @terdon I guess so. My example in the post was just simplified for the questions. This is my final script: pastebin.com/07ashrjWCommentedMar 13, 2020 at 14:21

1 Answer 1

2

Use a variable reference via declare -n refvar=$varname:

#!/bin/bash declare -a bff=("Abnehmen" "Buecher" "Dating" "Dating" "Fitness" "Handy" "Hunde" "Reisen" "Schmuck" "Schwanger" "Uhren") declare -a dab=("baby" "beauty" "fitness" "haushalt" "heimwekren") for product in bff dab; do echo "${product[@]}" #works fine, it echoes 'bff' in the first loop declare -n parray=$product for sub in "${parray[@]}"; do echo "${product}/${sub}" #does not work, echoes 'bff/0' done done bff bff/Abnehmen bff/Buecher bff/Dating bff/Dating bff/Fitness bff/Handy bff/Hunde bff/Reisen bff/Schmuck bff/Schwanger bff/Uhren dab dab/baby dab/beauty dab/fitness dab/haushalt dab/heimwekren 
1
  • Thank you very much. This is working. You are the best. I need to wait six minutes to accept you answer.CommentedMar 13, 2020 at 11:49

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.