免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4439 | 回复: 6
打印 上一主题 下一主题

while循环输入输出重定向的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-05-24 12:14 |只看该作者 |倒序浏览
在unix.shell.by.example.4.edition这本书里,讲到关于在循环语句中使用重定向的问题的时候,举了个例子。意思是说,如果在循环语句中使用了重定向,会生成subshell来处理重定向,在循环体中定义的变量,只对这个subshell有效,退出循环体后(也就是退出了subshell)这些变量就不存在了。但是我实验的结果不是这样的,最后显示的是Hi there JOE,也就是说循环体中定义的name,在循环体外也可以使用,与书上说的不符啊,我用的是bash 3.2.39.


书上的内容:
(The Input File)

$ cat testing

apples

pears

peaches



(The Script)

     #!/bin/sh

     # This program demonstrates the scope of variables when

     # assigned within loops where the looping command uses

     # redirection. A subshell is started when the loop uses

     # redirection, making all variables created within the loop

     # local to the shell where the loop is being executed.

1    while read line

     do

2        echo $line    # This line will be redirected to outfile

3        name=JOE

4    done < testing > outfile  # Redirection of input and output

5    echo Hi there $name



(The Output)

5    Hi there                                                  #这是书上的输出,我的输出是 Hi there JOE

论坛徽章:
0
2 [报告]
发表于 2009-05-24 12:51 |只看该作者
这有篇文章。

http://hi.baidu.com/ʫչ/blog/item/24e6951315fce5806438db1e.html

论坛徽章:
0
3 [报告]
发表于 2009-05-24 13:17 |只看该作者
原帖由 nomyself 于 2009-5-24 12:51 发表
这有篇文章。

http://hi.baidu.com/ʫչ/blog/item/24e6951315fce5806438db1e.html

谢谢,看过了那篇文章,试了第一个例子。我输出的count不是0,而是输入文件的行数。

[ 本帖最后由 simonlive 于 2009-5-24 13:30 编辑 ]

论坛徽章:
1
荣誉会员
日期:2011-11-23 16:44:17
4 [报告]
发表于 2009-05-24 13:40 |只看该作者
cat testing|while;do name=JOE;done >outfile;echo $name

论坛徽章:
0
5 [报告]
发表于 2009-05-24 13:56 |只看该作者
原帖由 simonlive 于 2009-5-24 13:17 发表

谢谢,看过了那篇文章,试了第一个例子。我输出的count不是0,而是输入文件的行数。


看了最后一句了吗?

以上的说法仅限于sh编程,对于ksh,bash,据我所知都不会有这个问题,它们处理的时候不会当作子shell来做。其它种类的shell可以自己试一试。

论坛徽章:
0
6 [报告]
发表于 2009-05-24 13:59 |只看该作者
原帖由 寂寞烈火 于 2009-5-24 13:40 发表
cat testing|while;do name=JOE;done >outfile;echo $name

谢谢你的回答。试过了,这次$name的值是空的。


书上写的是:
The shell starts a subshell to handle I/O redirection and pipes. Any variables defined within the loop will not be known to the rest of the script when the loop terminates.

但是实验的结果是,使用重定向的时候没有subshell,而使用管道的时候,才用了subshell。是这样的吗?


论坛徽章:
0
7 [报告]
发表于 2009-05-24 15:50 |只看该作者
原帖由 nomyself 于 2009-5-24 13:56 发表


看了最后一句了吗?

以上的说法仅限于sh编程,对于ksh,bash,据我所知都不会有这个问题,它们处理的时候不会当作子shell来做。其它种类的shell可以自己试一试。


哦,原来是这样!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP