Let Me Tink About It
Let Me Tink About It

Reputation: 16102

Iterating over arrays, each with a pair of values, to operate on each pair in turn

I already know how to generate pairs by taking one variable from each of a set of arrays, as such:

#!/bin/bash
dir1=(foo baz)  # Not ideal: Want inputs to be dir1=(foo bar); dir2=(baz bat) instead
dir2=(bar bat)
for i in "${!dir1[@]}"
do
  echo "Comparing ${dir1[i]} to ${dir2[i]}"
done

Produces the following output.

Comparing foo to bar
Comparing baz to bat


Is there a way to do this loop with foo bar on the same line and baz bat on it's same line? As follows.

pair1=(foo bar)
pair2=(baz bat)
...
pairN=(qux quux)
...
do
  # then, inside the loop, compare the pair
done

Upvotes: 1

Views: 95

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295325

You can use ${!prefix@} to iterate over variable names starting with prefix, and namerefs to refer to content stored under each name:

#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*|4.[012].*) echo "ERROR: Bash 4.3 required" >&2; exit 1;; esac

pair1=(foo bar)
pair2=(baz bat)
pairN=(qux quux)

declare -n currPair
for currPair in "${!pair@}"; do
  echo "Comparing ${currPair[0]} to ${currPair[1]}"
done

See this running at https://ideone.com/pTehPZ

Upvotes: 3

Related Questions