shell 脚本支持从管道读取

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/swgshj/article/details/78674981

testpipe.sh

#!/bin/bash

if [ $# -gt 0 ];then
    exec 0<$1;    #将文件绑定到标准输入(0-标准输入 1-标准输出 3-标准错误),默认第一个参数是输入的文件;
fi

while read line
do
    echo $line;
done<&0;    #从标准输入读取数据
exec 0<&-   #关闭标准输出。(是否也意味着解除之前的文件绑定??)

使用方法

cat a.txt | ./testpipe.sh

or

./testpipe.sh a.txt

下面链接对标准输入和输出的绑定有详细介绍
http://www.tldp.org/LDP/abs/html/x17974.html

猜你喜欢

转载自blog.csdn.net/swgshj/article/details/78674981