如何使用间接引用遍历数组? [英] How to iterate over an array using indirect reference?

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

问题描述

我怎样才能使这段代码工作?

How can I make this code work?

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

此代码:

echo ${!ARRAYNAME[0]}

打印苹果.我正在尝试做类似的事情,但使用[@]"来遍历数组.

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

提前致谢,

推荐答案

${!ARRAYNAME[@]} 的意思是ARRAYNAME 的索引".正如 bash 手册页中所述,因为 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.

这是一个使用 eval 的解决方案.

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 中引入的,旨在在尝试在 shell 中实现类似反射的行为时在很大程度上取代对 eval 的需求.


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

<小时>

综上所述,在这个简单的示例中使用间接引用是一回事,但是,正如 Dennis Williamson 提供的链接中所指出的,您应该对在实际脚本中使用它们犹豫不决.它们几乎肯定会使您的代码比必要的更加混乱.通常,您可以使用关联数组获得所需的功能.


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天全站免登陆