如何在 Bash 中迭代关联数组 [英] How to iterate over associative arrays in Bash

查看:31
本文介绍了如何在 Bash 中迭代关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于 Bash 脚本中的关联数组,我需要对其进行迭代以获取键和值.

Based on an associative array in a Bash script, I need to iterate over it to get the key and value.

#!/bin/bash

declare -A array
array[foo]=bar
array[bar]=foo

我实际上不明白如何在使用 for-in 循环时获取密钥.

I actually don't understand how to get the key while using a for-in loop.

推荐答案

使用感叹号访问键:${!array[@]}values 使用 ${array[@]} 访问.

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

您可以像这样迭代键/值对:

You can iterate over the key/value pairs like this:

for i in "${!array[@]}"
do
  echo "key  : $i"
  echo "value: ${array[$i]}"
done

注意在 for 语句中使用引号将变量括起来(加上使用 @ 而不是 *).这是必要的,以防任何键包含空格.

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

另一个答案中的混淆来自这样一个事实,即您的问题包括键值的foo"和bar".

The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.

这篇关于如何在 Bash 中迭代关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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