linux 管道产生子shell

来源:互联网 发布:黑马程序员php视频 编辑:程序博客网 时间:2024/05/16 10:28

linux中使用管道,下一个命令会放在子shell中执行,子shell中是不能访问主shell的变量

hadoop@hadoop:~$ cat file.txt
hanxin

hadoop@hadoop:~$ me=weihongrao
hadoop@hadoop:~$ cat file.txt | while read line;do me=$line;echo "inner me is:${me}";done;echo "outer me is :${me}";
inner me is:hanxin
outer me is :weihongrao
hadoop@hadoop:~$

以上在外部定义了一个变量me值为:weihongrao, 文件file.txt中有另一个名字hanxin,想要用file.txt中的名字替换主shell中的me变量,如果用管道的办法如上是行不通的因为管道产上子shell后while在子shell中执行,子shell 不能访问主shell中的me变量,所以结果如上达不到目的。


方案1

hadoop@hadoop:~$ while read line;do me=$line;echo "inner me is :${line}";done<file.txt;echo "outer me is :${me}";
inner me is :hanxin
outer me is :hanxin
hadoop@hadoop:~$

方案2;

exec 3<&0;。。。。。。。略

0 0