在Bash循环中设置变量

Mar*_*ada 2 bash scripting scope

刚开始学习Linux Bash Shell编程,我只是不知道我是否理解正确.看下面的示例程序:

#!/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
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

我不知道为什么总和仍然会回到RSS = 1000和SZ = 2000.我实际上期待RSS = 4780和SZ = 82679.

我知道我遗漏了一些基本的东西.我正在通过编写简单的脚本来学习bash.

Chr*_*aes 5

你应该避免使用@linuxfan提出的管道.您可以将代码更改为:

while read c1 c2 c3 c4 c5 c6 c7 c8 c9 c10
do
    ...
done < <(ps -ly)
Run Code Online (Sandbox Code Playgroud)

这样你的变量就会保持在同一范围内.