1. 程式人生 > >Shell變數while迴圈內改變無法傳遞到迴圈外

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,程式執行正常