- 论坛徽章:
- 0
|
在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
|
|