Skip to content

Linux 管道:标准输出、错误输出与退出状态 ​

| 把左侧标准输出(文件描述符 1)交给右侧标准输入(0);错误输出是 2,不会自动进入管道。以下使用 Bash 5.2。先进入空目录,确保里面没有 test1.sh:

bash
mkdir -p /tmp/linux-walkthrough/pipe
cd /tmp/linux-walkthrough/pipe

每一步沿用上一步生成的 test.sh。

读出test.sh文件内容,通过管道转发给grep 作为输入内容 ​

bash
printf 'echo ready\nexit 0\n' > test.sh
cat test.sh | grep -n 'echo'

本次输出 1:echo ready:行号是 1,匹配内容是 echo ready。单纯搜索文件可简写 grep -n 'echo' test.sh。

cat test1.sh不存在,错误输出打印到屏幕,正确输出通过管道发送给grep ​

确认练习目录中 test1.sh 不存在,再执行:

bash
cat test.sh test1.sh | grep -n 'echo'

本次分别得到一行错误和一行匹配,二者在终端的先后顺序可能变化:

text
cat: test1.sh: No such file or directory
1:echo ready

接着执行 printf 'default pipeline status: %s\n' "$?",得到 default pipeline status: 0。cat 读文件失败,最后一个 grep 却找到了匹配,因此整个管道默认仍返回成功。下一节先观察如何单独处理错误输出。

将test1.sh 没有找到错误输出重定向输出给/dev/null 文件,正确输出通过管道发送给grep ​

bash
cat test.sh test1.sh 2>/dev/null | grep -n 'echo'

本次只剩 1:echo ready。这只隐藏左侧错误,缺失文件仍未恢复。需要保存错误时,改用:

bash
cat test.sh test1.sh > combined.log 2>&1
printf 'cat status: %s\n' "$?"
cat combined.log

本次输出:

text
cat status: 1
echo ready
exit 0
cat: test1.sh: No such file or directory

combined.log 同时收下正文和错误,cat 的失败状态也保留了。需要把错误也交给后续命令时,用 2>&1;>log 2>&1 与 2>&1 >log 顺序不同。

读取test.sh内容,通过管道发送给ls命令,由于ls 不支持标准输入,因此数据被丢弃 ​

在还没生成 combined.log 的空练习目录里,本次 cat test.sh | ls 只输出 test.sh,没有输出 echo ready。这是 ls 列出的目录项。执行过上一节的保存命令后,还会列出 combined.log。

cat test.sh | ls 不会把文本行当作路径参数;ls 没有按行读取文件名的行为。按名称搜索路径可直接用 find . -name '*.sh'。

Bash 默认以最后一个命令的状态作为管道状态。需要发现左侧失败时:

bash
set -o pipefail
cat test.sh test1.sh | grep echo
printf 'pipeline status: %s\n' "$?"
set +o pipefail

本次终端有缺失文件错误和 echo ready,状态行变为 pipeline status: 1。与前面的默认状态 0 对照,就能看到 pipefail 的作用。最后一行关闭 pipefail,避免影响当前 shell 后续练习。grep 无匹配的退出码也是 1,脚本要区分无匹配和读取失败;不要把任意文本管道直接送给 sh 执行。

官方资料 ​

最近更新