间接引用bash中的数组值

编程入门 行业动态 更新时间:2024-10-24 09:27:26
本文介绍了间接引用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中的数组值

本文发布于:2023-11-04 01:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556534.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!