• 管道输出到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 "
    All done, last:$last
    "
    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
  • 相关阅读:
    钱伟长的养生之道:每天步行三千步
    GBDT 深入理解
    整形数据的存储方式
    进制基础学习
    C语言运算符(注意事项)
    PHP文件锁
    gcc options选项的优化及选择
    Datenode无法启动
    如何使用WebUploader。
    thinkphp如何实现伪静态
  • 原文地址:https://www.cnblogs.com/fly-xiang-zhao/p/3948874.html
Copyright © 2020-2023  润新知