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

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

2 .while被放置在子shell中。

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

 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

 linux shell数据重定向(输入重定向与输出重定向)详细分析

linux shell 管道命令(pipe)使用及与shell重定向区别

转载于:https://my.oschina.net/flyxiang/blog/343738

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值