再概括下:
从上面例子可以看,重定向与管道在使用时候很多时候可以通用,其实,在shell里面,经常是【条条大路通罗马】的。一般如果是命令间传递参数,还是管道的好,如果处理输出结果需要重定向到文件,还是用重定向输出比较好。
命令执行顺序可以看下:Linux Shell 通配符、元字符、转义符使用实例介绍
shell脚本接收管道输入
有意思的问题:
既然作用管道接收命令,需要可以接收标准的输入,那么我们shell脚本是否可以开发出这样的基本程序呢?(大家经常看到的,都是一些系统的命令作为管道接收方)
实例(testpipe.sh):
#!/bin/sh if [ $# -gt 0 ];then exec 0<$1; #判断是否传入参数:文件名,如果传入,将该文件绑定到标准输入 fi while read line do echo $line; done<&0; #通过标准输入循环读取内容 exec 0&-; #解除标准输入绑定
运行结果:
[chengmo@centos5 shell]$ cat testpipe.txt 1,t,est pipe 2,t,est pipe 3,t,est pipe 4,t,est pipe #testpipe.txt 只是需要读取的测试文本 [chengmo@centos5 shell]$ cat testpipe.txt | sh testpipe.sh 1,t,est pipe 2,t,est pipe 3,t,est pipe 4,t,est pipe #通过cat 读取 testpipe.txt 发送给testpipe.sh 标准输入 [chengmo@centos5 shell]$ sh testpipe.sh testpipe.txt 1,t,est pipe 2,t,est pipe 3,t,est pipe 4,t,est pipe #testpipe.sh 通过出入文件名读取文件内容










