Shell變量while循環(huán)內(nèi)改變無法傳遞到循環(huán)外

今天刷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:

# the4

# is3

# sunny2

# day1

# define a map

declare -A map=()

# iterator lines in file

L24 #cat words.txt |whileread line

whileread line

do

forword in $line

do

? ? ? ? echo $word

if[ -z ${map[$word]} ];then

map[$word]=1

else

? ? ? ? ? ? let map[$word]++

? ? ? ? fi?

? ? done

L36done < words.txt

forkey in ${!map[@]}

do

? ? echo $key ${map[$key]}

done

題目的意思是統(tǒng)計一個文件中單詞重復的次數(shù),開始寫法如L24,while循環(huán)結(jié)束后,map依然為空,后來才知道是使用了管道的緣故

當啟用管道時,會生成一個subshell,while循環(huán)的代碼在subshell中執(zhí)行,那么變量map也是在subshell中被修改,

while循環(huán)結(jié)束后,回到主shell,map沒有被修改,也就是說,兩個map不是同一個map,while中修改的map是外層map的副本

修改代碼,將讀取文件的格式改成L36,程序運行正常

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容