bash - 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
谷歌搜索错误只会导致“您的数组格式不正确”的结果。
解决方案
您可以从串行变量输入中读取键/值对:
$ 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
无论键和值是什么,这都应该是安全的。
推荐阅读
- powerbi - 为什么保存度量时 Power Bi 会冻结?
- javascript - 将新对象推送到嵌套对象
- python - is there a way to loop through an array of images to find which one has been clicked in pygame?
- c++ - C++主动异常机制背后的推理
- pdf - 以 PDF 格式键入 0 函数;我在看什么?
- excel - 显示最新版本 VBA
- compilation - 如何将 Julia 编译为可执行文件(Windows 机器)
- entity-framework - VS2017 上带有 EF 的 Abp 5.0 模板问题
- c# - 序列化/访问 ExtensionDataObject
- python - 全局变量中的 Python API 连接 - 分配不起作用