https://www.cnblogs.com/yeungchie/
定义
declare -A dict
赋值
批量赋值
dict=([a]=1 [b]=2 [c]=3)
追加赋值
dict[lib]=top
dict[cell]=XX1234
dict[view]=layout
取值
取值方式与数组一样。
echo "${dict[a]}"
# 1
echo "${dict[cell]}"
# XX1234
打印所有 key 和 value
echo ${!dict[*]}
# cell view a b c lib
echo ${dict[*]}
# XX1234 layout 1 2 3 top
for k in ${!dict[*]}; do
echo "$k ${dict[$k]}"
done
# cell XX1234
# view layout
# a 1
# b 2
# c 3
# lib top
存在的问题
不建议 key 中有空格,虽然可以赋值和取值,但无法正确遍历。
dict[q w e]=123
创建一个 key 为 "q w e",这里加不加引号效果一样
可以正常取值:
echo ${dict[q w e]}
# 123
key="q w e"
echo ${dict[$key]}
# 123
遍历一下:
for k in ${!dict[*]}; do
echo "$k ${dict[$k]}"
done
# cell XX1234
# view layout
# a 1
# b 2
# c 3
# lib top
# q
# w
# e
标签:Shell,layout,echo,cell,XX1234,dict,key,Bash,字典 From: https://www.cnblogs.com/yeungchie/p/17487767.html无法区分 "q w e" 还是 "q", "w", "e"