Linux 管道符:用 | 串联指令处理数据流
两条命令用 | 连起来时,左边写入 standard output(标准输出)的数据会进入管道。报错走 standard error(标准错误),从管道传过去的数据则由右边通过 standard input(标准输入)读取。
TIP
- 左侧命令的报错会绕开管道,送过去的是标准输出。
- 右侧命令得能从标准输入读取数据。
用 grep 筛选从 test.sh 读出的文本
sh
cat test.sh | grep -n 'echo'
5: echo "very good!";
7: echo "good!";
9: echo "pass!";
11: echo "no pass!";读不到 test1.sh 时在终端显示报错,grep 仍从管道读取标准输出
sh
cat test.sh test1.sh | grep -n 'echo'
cat: test1.sh: 没有那个文件或目录
5: echo "very good!";
7: echo "good!";
9: echo "pass!";
11: echo "no pass!";把找不到 test1.sh 的报错送入 /dev/null,grep 只接收正常输出
sh
cat test.sh test1.sh 2>/dev/null | grep -n 'echo'
5: echo "very good!";
7: echo "good!";
9: echo "pass!";
11: echo "no pass!";从 test.sh 读出的文本传给 ls 后会被丢弃,因为 ls 不读标准输入
sh
cat test.sh | ls
catfile httprequest.txt secure test testfdread.sh testpipe.sh testsh.sh testwhile2.sh
envcron.txt python sh testcase.sh testfor2.sh testselect.sh test.txt text.txt
env.txt release sms testcronenv.sh testfor.sh test.sh testwhile1.sh