bash - 如何在 Bash 中定义哈希表?

标签 bash dictionary hashtable associative-array

什么相当于Python dictionaries但在 Bash 中(应该跨 OS X 和 Linux 工作)。

最佳答案

狂欢 4

Bash 4 原生支持此功能。确保你的脚本的 hashbang 是 #!/usr/bin/env bash#!/bin/bash 这样你就不会最终使用 sh。确保您是直接执行脚本,或者使用 bash 脚本 执行script。 (实际上并没有用 Bash 执行 Bash 脚本确实发生了,而且会真的令人困惑!)

通过以下方式声明关联数组:

declare -A animals

您可以使用普通的数组赋值运算符用元素填充它。例如,如果你想要一张 animal[sound(key)] = animal(value) 的 map :

animals=( ["moo"]="cow" ["woof"]="dog")

或者在一行中声明和实例化:

declare -A animals=( ["moo"]="cow" ["woof"]="dog")

然后像普通数组一样使用它们。使用

  • animals['key']='value'设置值

  • "${animals[@]}" 扩展值

  • "${!animals[@]}"(注意 !)扩展键

不要忘记引用它们:

echo "${animals[moo]}"
for sound in "${!animals[@]}"; do echo "$sound - ${animals[$sound]}"; done

狂欢 3

在 bash 4 之前,您没有关联数组。 不要使用eval 来模拟它们。避免 eval 之类的瘟疫,因为它 是 shell 脚本的瘟疫。最重要的原因是 eval 将您的数据视为可执行代码(还有许多其他原因)。

首先:考虑升级到 bash 4。这将使整个过程对您来说更容易。

如果您有理由无法升级,declare 是一个更安全的选择。它不像 eval 那样像 bash 代码那样评估数据,因此不允许任意代码注入(inject)。

让我们通过介绍概念来准备答案:

首先,间接。

$ animals_moo=cow; sound=moo; i="animals_$sound"; echo "${!i}"
cow

其次,声明:

$ sound=moo; animal=cow; declare "animals_$sound=$animal"; echo "$animals_moo"
cow

将它们放在一起:

# Set a value:
declare "array_$index=$value"

# Get a value:
arrayGet() { 
    local array=$1 index=$2
    local i="${array}_$index"
    printf '%s' "${!i}"
}

让我们使用它:

$ sound=moo
$ animal=cow
$ declare "animals_$sound=$animal"
$ arrayGet animals "$sound"
cow

注意:declare 不能放在函数中。在 bash 函数内使用 declare 会将它创建的变量 local 转换为该函数的范围,这意味着我们无法使用它访问或修改全局数组。 (在 bash 4 中,您可以使用 declare -g 来声明全局变量 - 但在 bash 4 中,您可以首先使用关联数组,从而避免这种变通方法。)

总结:

  • 升级到 bash 4 并为关联数组使用 declare -A
  • 如果无法升级,请使用declare 选项。
  • 考虑改用 awk 并完全避免该问题。

关于bash - 如何在 Bash 中定义哈希表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666055/

相关文章:

bash - 这段代码在做什么? :(){:|:&};:

c# - 字典错误调试中不存在给定的键

javascript - 限制mapbox中的叠加

c++ - 多键哈希表(unordered_map)

linux - 通过 Bash 登录站点 (Stack Overflow)

bash - 防止 `less -R` 跨换行重置颜色

bash - 修复 bash vi 输入模式中的 <right arrow>。不能输入超过最后一个字符

c# - 我如何将 List<Dictionary<string, object>> 转换为 List<[具有动态属性的新类]>

java - 如何从哈希表中删除特定日期的数据

c - 使用 GSList 作为 GHashTable 值的不同方法