0

I have 2 arrays that refer to files for example

alpha=file 1
beta=file2
Charlie=file3
delta=file4
beta2=file5
beta3=file6
Charlie2=file7
charlie3=file8
delta2=file9
delta3=file10

array1=("$alpha" "$beta" "$Charlie" "$delta)
array2=("$beta2" "$beta3" "$Charlie2" "$Charlie3" "$delta1 "$delta3")

Then I have an algorithm that goes through and uses these files together example

for ((i=0;2;i++))
do
   for((j=0;2;j++))
   do
     ./${array1[$i]}.sh ${array2[$j]}.in        
   done
done

Problem is I would like the array1 and array 2 to correspond such that

it would be for example

./file2.sh file5.in

But I can never get it to do it because of course when j resets for each loop of i. What is the solution for this?

2
  • bash is not an ideal language for using 2d arrays. Choose other language for your project. Dec 12, 2018 at 15:51
  • Is there a better way to do this in bash. I have no option other to use bash at the moment.
    – OB1
    Dec 12, 2018 at 15:53

2 Answers 2

3

If you want the 1st item of array1 to correspond to the 1st item of array2, then you don't need nested loops: just use the same index variable

for i in {0..2}; do
    "./${array1[i]}.sh" "${array2[i]}.in"
    # ..........^.................^
done

Or, use an associative array:

declare -A map=(
    [$alpha]=$beta2
    [$beta]=$beta3
    [$Charlie]=$Charlie2
    [$delta]=$Charlie3
)

for key in "${!map[@]}"; do
    do_something_with "$key" and "${map[$key]}"
done
2
  • There's no guarantee about the order of the keys in the for loop for an associative array. Dec 12, 2018 at 16:19
  • I think I have got round the issue by getting rid of the nested loops and made array 1 same size as array 2 by repeating the declarations for each element of array 2. This seems to work!
    – OB1
    Dec 12, 2018 at 16:47
0

Sounds like you want an array zipping operator, then zsh may be a better option than bash here:

$ a=({A..D}) b=({1..10})
$ for i j (${a:^b}) echo $i $j
A 1
B 2
C 3
D 4
$ for i j (${a:^^b}) echo $i $j
A 1
B 2
C 3
D 4
A 5
B 6
C 7
D 8
A 9
B 10

${a:^b} and ${a:^^b} are two array zipping parameter expansion operators. The difference is seen when one array has fewer elements than the other, in which case the latter will reuse the elements from the shorter one to match the larger one.

Note that leaving a variable unquoted in zsh doesn't have the same nasty side effects as in other Bourne-like shells, but still removes empty elements. So, if your arrays may contain empty elements, you would need to write it:

for i j ("${(@)a:^^b}") echo "$i" "$j"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .