在Bash循环内设置变量 [英] Setting variables inside a Bash loop
本文介绍了在Bash循环内设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
刚刚开始学习Linux Bash Shell编程,而我只是不知道我是否正确理解它.查看下面的示例程序:
Just started learning Linux Bash Shell Programming, and I just don't know if I understood it correctly. Looking at the sample program below:
#!/bin/bash
n=1
sumRSS=1000
sumSZ=2000
echo Before sumRSS=$sumRSS sumSZ=$sumSZ
ps -ly | while
read c1 c2 c3 c4 c5 c6 c7 c8 c9 c10
do
if (( n>1 ))
then
echo n=$n rss=$sumRSS sz=$sumSZ
((sumRSS = sumRSS + c8))
((sumSZ = sumSZ + c9))
fi
((n++))
done
echo Sum of RSS = $sumRSS
echo Sum of SZ = $sumSZ
输出:
Before sumRSS=1000 sumSZ=2000
n=2 rss=1000 sz=2000
n=3 rss=2368 sz=29118
n=4 rss=3792 sz=55644
n=5 rss=4780 sz=82679
Sum of RSS = 1000
Sum of SZ = 2000
我不知道为什么总和仍然回到RSS = 1000和SZ = 2000.我实际上期望的是RSS = 4780和SZ = 82679.
I don't know why the sum still goes back to RSS=1000 and SZ=2000. I actually was expecting RSS=4780 and SZ=82679.
我知道我缺少一些基本知识.我正在通过编写简单的脚本来学习bash.
I know I am missing something basic. I am learning bash by writing simple scripts.
推荐答案
您应该避免使用@linuxfan建议的管道.您可以将代码更改为:
you should avoid the pipe as @linuxfan proposes. You can change your code to:
while read c1 c2 c3 c4 c5 c6 c7 c8 c9 c10
do
...
done < <(ps -ly)
这样,您的变量将保持在同一范围内.
this way your variables stay in the same scope.
这篇关于在Bash循环内设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文