如何循环在bash关联数组 [英] How to iterate over associative array in bash

查看:192
本文介绍了如何循环在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.

推荐答案

键是使用感叹号访问:{!数组[@]} $ 的< STRONG>的的使用被访问 $ {数组[@]}

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

请注意围绕在语句中的变量使用引号(加@ 使用的而不是 * )。这是必要的情况下,任何的键包含空格。

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和酒吧这两个键的的值。

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