管道输出到read中遇到的问题

1. 管道输出到read命令中, 使用管道echo输出来设置变量将会失败. 然而, 使用管道cat输出看起来能够正常运行.   cat file1 file2 |  while read line

2 .while被放置在子shell中。

1 #!/bin/sh
2 # readpipe.sh
3 #  Bjon Eriksson .
4
5 last="(null)"
6 cat $0 |
7 while read line
8 do
9 echo "{$line}"
10 last=$line
11 done
12 printf "\nAll done, last:$last\n"
13
14 exit 0 # 代码结束.
15 # 下边是脚本的(部分)输出.
16 # 'echo'出了多余的大括号.
17
18 #############################################
19
20 ./readpipe.sh 
21
22 {#!/bin/sh}
23 {last="(null)"}
24 {cat $0 |}
25 {while read line}
26 {do}
27 {echo "{$line}"}
28 {last=$line}
29 {done}
30 {printf "nAll done, last:$lastn"}
31
32
33 All done, last:(null)
34
35 变量(last)被设置在子shell中, 并没有被设置在外边. 
在许多Linux发行版上, gendiff脚本通常都在/usr/bin下, 将find的输出通
过管道传到while read结构中.
1 find $1 \( -name "*$2" -o -name ".*$2" \) -print |
2 while read f; do
3 . . .

 3. 例外,在pipe中的一个大括号中的代码段可能运行在一个 子shell中   。

 ls | { read firstline; read secondline; }        echo "First line is $firstline; second line is $secondline" # 不能工作

4. 引用还可以改掉echo's不换行的"毛病".

bash$ echo $(ls -l)
total 8 -rw-rw-r-- 1 bozo bozo 130 Aug 21 12:57 t222.sh -rw-rw-r-- 1 bozo bozo 78 
Aug 21 12:57 t71.sh
bash$ echo "$(ls -l)"
total 8
-rw-rw-r-- 1 bozo bozo 130 Aug 21 12:57 t222.sh
-rw-rw-r-- 1 bozo bozo 78 Aug 21 12:57 t71.sh

 

转载于:https://www.cnblogs.com/fly-xiang-zhao/p/3948874.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值