shell 的关联数组
引言
shell也有Map的数据结构,哈哈哈,是挺高大上的。万能的shell。。。。
万恶的mac,sed和linux不一样,关联数组和linux也不要一样。要你干啥!!!
一个需求的处理
感谢这个博客https://my.oschina.net/uyinn/blog/266844,不然我还在mac上弄,为啥关联数组就不好使了呢?
问题
把字符串abc=123,tom=456,lixi=789
赋值给abc、tom、lixi
三个变量
思路
字符串 -> 数组 -> 关联数组 -> 赋值给变量
代码
#!/bin/bash
STR='abc=123,tom=456,lixi=789'
function string_var() {
# change to array
local str=(`echo ${STR} | tr ',' ' '`)
echo "str: ${str[@]}"
# change to ass array
declare -A str_dict
for mapping in "${str[@]}"
do
str_dict["${mapping%=*}"]=${mapping#*=}
done
tom=str_dict['tom']
lixi=str_dict['lixi']
abc=str_dict['abc']
for k in "${!str_dict[@]}"
do
echo $k '--' ${str_dict[$k]}
done
}
string_var
结果
[root@04dd48aa710b bin]# sh str.sh
str: abc=123 tom=456 lixi=789
lixi -- 789
abc -- 123
tom -- 456