首页 > 解决方案 > 遍历数组,每个数组都有一对值,依次对每一对进行操作

问题描述

我已经知道如何通过从一组数组中的每一个中获取一个变量来生成对,如下所示:

#!/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

产生以下输出。

比较 foo 和 bar
比较 baz 和 bat


有没有办法foo bar在同一行和同一行baz bat上执行此循环?如下。

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

标签: bashshellloops

解决方案


您可以使用${!prefix@}迭代以prefixnamerefs开头的变量名称来引用存储在每个名称下的内容:

#!/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

在https://ideone.com/pTehPZ看到这个运行


推荐阅读