bash - 遍历数组,每个数组都有一对值,依次对每一对进行操作
问题描述
我已经知道如何通过从一组数组中的每一个中获取一个变量来生成对,如下所示:
#!/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
解决方案
您可以使用${!prefix@}
迭代以prefix
和namerefs开头的变量名称来引用存储在每个名称下的内容:
#!/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
推荐阅读
- ms-access - 更改附加到 ListBox 的 ADODB.Recordset 的光标位置是否保存?
- r - 在 R 中使用复杂的填充规则将向量重塑为更大的矩阵
- javascript - 使用 javascript 检查 css 文件中的选择器重复项
- git - 从已经在 PR 中的 PR 中排除提交
- mysql - SQL - 在 Mysql 中将一列拆分为两列
- c++ - 类成员重新排序
- c - 生成遵循特定分布的随机双打
- javascript - You Don't Know JS: Up & Going - 示例问题
- javascript - 使用 G-Sheet 中的 SDK v8 打印到 Dymo 失败
- java - Hibernate + JPA:非空属性引用空值或瞬态值