你没说自己用的是什么 shell, 但是在大部分的 shell 里, 管道的命令经常是在 subshell 里执行的,在 subshell 里对变量做的更改,是没办法在 subshell 外部获取的。
不同的 shell 表现不一样,BASH 是这样的:仅当 loop 是管道的最后一部分,才会创建一个 subshell (也就是你写的脚本的场景)
解决思路是去掉管道。以 BASH 为例:
1. 用文件当作输入
把 df -PT
的输出写到一个临时文件,把临时文件的内容用 <
重定向一下
2. Command grouping
把 df -PT
以外的处理都放一起
df -PT |
{
while read line
do
linecount=$((linecount + 1))
done
echo "$linecount"
}
3. ProcessSubstitution
while read line
do
linecount=$((linecount + 1))
done < <(df -PT)
echo "$linecount"
4. HereString
while read line
do
linecount=$((linecount + 1))
done <<< $(df -PT)
echo "$linecount"
5. named pipe
mkfifo p
df -PT > p &
while read line
do
linecount=$((linecount + 1))
done < p
echo "$linecount"
不止上面这些,肯定还有不少方法可以绕过