declare -A map=()
#cat words.txt | while read line
while read line
do
for word in $line
do
echo $word
if [ -z ${map[$word]} ];then
map[$word]=1
else
let map[$word]++
fi
done
done < words.txt
for key in ${!map[@]}
do
echo $key ${map[$key]}
done
错误写法如第三行,while循环结束后,map依然为空,这是因为启用管道时,会生成一个subshell,while循环的代码在subshell中执行,那么变量map也是在subshell中被修改,当while循环结束后,回到主shell,map没有被修改,也就是说,两个map不是同一个map,while中修改的map是外层map的副本,修改代码,将读取文件的格式改成第四行,程序运行正常