Shell變量while循環內改變無法傳遞到循環外

今天刷Leecode(192 Word frequency)時,遇到一個shell語法問題,記錄下來。首先將題目描述和代碼呈上

#!/bin/bash

# Write a bash script to calculate the frequency of each word in a text file words.txt.
#
# For simplicity sake, you may assume:
#  words.txt contains only lowercase characters and space ' ' characters.
#  Each word must consist of lowercase characters only.
#  Words are separated by one or more whitespace characters.
#
# For example, assume that words.txt has the following content:
# the day is sunny the the
# the sunny is is
#
# Your script should output the following, sorted by descending frequency:
# the 4
# is 3
# sunny 2
# day 1

# define a map
declare -A map=()

# iterator lines in file
#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
 題目的意思是統計一個文件中單詞重複的次數,開始寫法如L24,while循環結束後,map依然爲空,後來才知道是使用了管道的緣故
 當啓用管道時,會生成一個subshell,while循環的代碼在subshell中執行,那麼變量map也是在subshell中被修改,
 while循環結束後,回到主shell,map沒有被修改,也就是說,兩個map不是同一個map,while中修改的map是外層map的副本
 修改代碼,將讀取文件的格式改成L36,程序運行正常
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章