Young87

当前位置:首页 >个人收藏

shell 使用管道符时变量的问题

文件如下:

test

1

2

3

4

5

使用命令

wc -l test

输出结果为

5 test


使用管道符计算文件行数脚本如下:

#!/bin/sh

linenum=0

cat test | while read line
do
    echo "line content: $line"
    ((linenum+=1))
done

echo "line number: $linenum"

输出结果为

line content: 1
line content: 2
line content: 3
line content: 4
line content: 5
line number: 0


使用重定向计算文件函数脚本如下:

#!/bin/sh

linenum=0

while read line
do
    echo "line content: $line"
    ((linenum+=1))
done < test

echo "line number: $linenum"

输出结果为

line content: 1
line content: 2
line content: 3
line content: 4
line content: 5
line number: 5


分析结果:

使用管道符时,会fork出一个子进程,变量在父子进程里无法互通。使用第二种方式,在同一个进程中,所以达到了我们预期的目的。



除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: windows内核情景分析---内核对象

下一篇: 几种范式(norm)

精华推荐