0

I've got the following problem: I got a config-file (written in bash) with multiple arrays, the amount of these arrays is different from config to config. Each array contains three values.

declare -a array0
array0=(value1 value2 value3)  
#  
declare -a array1  
array1=(value1 value2 value3)  
#  
declare -a array2  
array2=(value1 value2 value3)      

Now, this config file is sourced into the main bash script. I want to go from array to array and store the values into single variables. My actual solution:

for ((i=0;i=2;i++))  
do  
 if [ "$i" = 0 ]  
 then  
  wantedvalue1="${array0["$i"]}"  
 fi  
 if [ "$i" = 1 ]  
 then  
  wantedvalue2="${array0["$i"]}"  
 fi  
 if [ "$i" = 2 ]  
 then  
  wantedvalue3="${array0["$i"]}"  
 fi  
done 

I guess, this will work for one specific array. But how can I tell the script to analyze every array in the config file like this?
Thanks for any help!

3
  • can't you just add another for loop? Commented Oct 28, 2014 at 11:19
  • it's possible that there will be 50 or more arrays.. I really don't want to place 50 for loops in my code. Commented Oct 28, 2014 at 11:22
  • 1
    Perhaps it's worth providing some more context here. What exactly are you trying to achieve in the end? Why do you need to make separate variables like this anyway? Commented Oct 28, 2014 at 11:39

1 Answer 1

1

You can find the arrays in your environment via set. This extracts the names of the arrays which have exactly three elements:

set | sed -n 's/^\([_A_Za-z][_A-Za-z0-9]*\)=(\[0]=.*\[2]="[^"]*")$/\1/p'

(The number of backslashes depends on your sed dialect. This worked for me on Debian, where backslashed parentheses are metacharacters for grouping, and bare parentheses are matched literally.)

I don't really see why you want to use a loop to extract just three elements, but the wacky indirect reference syntax in bash kind of forces it here.

for array in $(set |
  sed -n 's/^\([_A_Za-z][_A-Za-z0-9]*\)=(\[0]=.*\[2]="[^"]*")$/\1/p'); do
    for((i=0, j=1; i<3; ++i, ++j)); do
         k="$array[$i]"
         eval wantedvalue$j=\'${!k}\'
    done
    :
    : code which uses the wantedvalues here
done

It would be a tad simpler if you just used another array for the wantedvalues. Then the pesky eval could be avoided, too.

Sign up to request clarification or add additional context in comments.

3 Comments

note - Triplee uses the nested loop suggested above (to close the loop)
finally I didn't use the loop - just the set/sed combination, this worked fine for me
@PaulBastide That's trivial. The substance is in obtaining the array names, and in the trickery in using them indirectly.

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.