Shell变量while循环内改变无法传递到循环外
2017-03-24 15:33
357 查看
今天刷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,程序运行正常
#!/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,程序运行正常
相关文章推荐
- Bash 外部变量在循环内改变无法传递到循环外
- shell 循环变量传递问题
- linux中的for、while循环输出中赋值变量及shell中循环获取脚本参数
- Bash shell,while 循环中的变量无法保存问题
- 从键盘输入一组非0整数,以输入0为结束标志,求这组整数的平均值,并统计其中正数和负数的个数。(根据循环变量的初值、终值无法判断出循环次数时建议使用while或do while语句完成)。
- Shell编程中使用管道循环中无法改变外部变量的解决办法
- Shell while 循环
- register_globals使用详解 为什么我的表单无法传递数据?为什么我的程序无法得到传递过来的变量?
- shell 关于 while 循环中赋值的问题
- Shell向Perl脚本中传递变量的方法
- Shell-while循环的例子
- shell & awk 变量传递+awk综合概要
- delphi 7 - delphi 2010 测试 for 循环中也能改变 循环变量的值为任意值
- c 的 for 循环中改变变量的值
- shell脚本学习:特殊变量和C语言格式循环
- 【转】父 shell,子 shell ,export 与 变量传递
- 关于while read line循环的linux bash shell bug
- [转]Awk基础入门之三:shell & awk 变量传递
- php无法进行变量传递的解决
- shell 循环中使用管道符的变量问题