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


轉自: https://blog.csdn.net/shawhe/article/details/65631543

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

 1 #!/bin/bash
 2  
 3 # Write a bash script to calculate the frequency of each word in a text file words.txt.
 4 #
 5 # For simplicity sake, you may assume:
 6 #  words.txt contains only lowercase characters and space ' ' characters.
 7 #  Each word must consist of lowercase characters only.
 8 #  Words are separated by one or more whitespace characters.
 9 #
10 # For example, assume that words.txt has the following content:
11 # the day is sunny the the
12 # the sunny is is
13 #
14 # Your script should output the following, sorted by descending frequency:
15 # the 4
16 # is 3
17 # sunny 2
18 # day 1
19  
20 # define a map
21 declare -A map=()
22  
23 # iterator lines in file
24 #cat words.txt | while read line
25 while read line
26 do
27     for word in $line
28     do  
29         echo $word
30         if [ -z ${map[$word]} ];then
31             map[$word]=1
32         else
33             let map[$word]++
34         fi  
35     done
36 done < words.txt
37  
38 for key in ${!map[@]}
39 do
40     echo $key ${map[$key]}
41 done

 題目的意思是統計一個文件中單詞重復的次數,開始寫法如L24,while循環結束后,map依然為空,后來才知道是使用了管道的緣故
 當啟用管道時,會生成一個subshell,while循環的代碼在subshell中執行,那么變量map也是在subshell中被修改,
 while循環結束后,回到主shell,map沒有被修改,也就是說,兩個map不是同一個map,while中修改的map是外層map的副本
 修改代碼,將讀取文件的格式改成L36,程序運行正常


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM