首页 > 解决方案 > Bash如何从参数解析关联数组?

问题描述

我正在尝试将字符串读入关联数组。

该字符串被正确转义并读入 .sh 文件:

./myScript.sh "[\"el1\"]=\"val1\" [\"el2\"]=\"val2\""

在脚本内

#!/bin/bash -e
declare -A myArr=( "${1}" ) #it doesn't work either with or without quotes

我得到的是:

line 2: myArr: "${1}": must use subscript when assigning associative array

谷歌搜索错误只会导致“您的数组格式不正确”的结果。

标签: bashassociative-array

解决方案


您可以从串行变量输入中读取键/值对:

$ cat > example.bash <<'EOF'
#!/usr/bin/env bash

declare -A key_values
while true
do
    key_values+=(["$1"]="$2")
    shift 2
    if [[ $# -eq 0 ]]
    then
        break
    fi
done

for key in "${!key_values[@]}"
do
    echo "${key} = ${key_values[$key]}"
done
EOF
$ chmod u+x example.bash
$ ./example.bash el1 val1 el2 val2
el2 = val2
el1 = val1

无论键和值是什么,这都应该是安全的。


推荐阅读