bash 中对数组值的间接引用 [英] Indirect reference to array values in bash

查看:39
本文介绍了bash 中对数组值的间接引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 bash 中对数组中的值进行间接引用.

I am trying to do an indirect reference to values in an array in bash.

anotherArray=("foo" "faa")

foo=("bar" "baz")
faa=("test1" "test2")


for indirect in ${anotherArray[@]}
do

echo ${!indirect[0]}
echo ${!indirect[1]}

done

这不起作用.我尝试了很多不同的方法来通过回显 $indirect 来获得 $foo 的不同值,但我只能获得第一个值、所有值、'0' 或什么都没有.

This does not work. I tried a lot of differenct things to get the different values of $foo by echoing $indirect but I can only get the first value, all values, '0' or nothing at all.

推荐答案

现代版本的 bash 采用了 ksh 特性namevars",非常适合这个问题:

Modern versions of bash adopt a ksh feature, "namevars", that's a perfect fit for this issue:

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

anotherArray=("foo" "faa")

foo=("bar" "baz")
faa=("test1" "test2")

for indirectName in "${anotherArray[@]}"; do
  declare -n indirect="$indirectName"
  echo "${indirect[0]}"
  echo "${indirect[1]}"
done

这篇关于bash 中对数组值的间接引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆