如何循环使用间接引用一个数组? [英] How to iterate over an array using indirect reference?

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

问题描述

我怎样才能让这个code的工作?

How can I make this code work?

#!/bin/bash
ARRAYNAME='FRUITS'
FRUITS=( APPLE BANANA ORANGE )
for FRUIT in ${!ARRAYNAME[@]}
do
    echo ${FRUIT}
done

这code:

echo ${!ARRAYNAME[0]}

打印苹果。我tryng做同样的,但东西[@]遍历数组。

Prints APPLE. I'm tryng to do something similar but with "[@]" to iterate over the array.

由于提前,

推荐答案

$ {!arrayName中的[@]} 表示 arrayName中的索引。由于自 bash的man页面说arrayName中设置,但作为一个字符串,而不是一个数组,它返回 0

${!ARRAYNAME[@]} means "the indices of ARRAYNAME". As stated in the bash man page since ARRAYNAME is set, but as a string, not an array, it returns 0.

下面是一个使用的解决方案评估

Here's a solution using eval.

#!/usr/bin/env bash

ARRAYNAME='FRUITS'
FRUITS=( APPLE BANANA ORANGE )

eval array=\( \${${ARRAYNAME}[@]} \)

for fruit in "${array[@]}"; do
  echo ${fruit}
done


您最初试图做的是创造一个间接参考。这些都是在bash 2版推出,注定要在很大程度上取代了需要评估时,试图达到壳反射般的行为。


What you were originally trying to do was create an Indirect Reference. These were introduced in bash version 2 and were meant to largely replace the need for eval when trying to achieve reflection-like behavior in the shell.

您有什么用使用数组间接引用的时候做的是包括 [@] 在猜测变量名:

What you have to do when using indirect references with arrays is include the [@] in your guess at the variable name:

#!/usr/bin/env bash

ARRAYNAME='FRUITS'
FRUITS=( APPLE BANANA ORANGE )

array="${ARRAYNAME}[@]"
for fruit in "${!array}"; do
  echo $fruit
done


所有这一切说,这是一件事在这个简单的例子来使用间接引用,但正如丹尼斯威廉姆森提供的链接所指出的,你应该犹豫在现实世界的脚本来使用它们。他们所有,但保证让你的code比必要更多的混乱。通常你可以得到你所需要的关联数组的功能。


All that said, it's one thing to use Indirect References in this trivial example, but, as indicated in the link provided by Dennis Williamson, you should be hesitant to use them in real-world scripts. They are all but guaranteed to make your code more confusing than necessary. Usually you can get the functionality you need with an Associative Array.

这篇关于如何循环使用间接引用一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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