puk*_*puk 2 bash shell stdout pipe
我可以像错误一样退出程序
ls /fake/folder || exit 1
Run Code Online (Sandbox Code Playgroud)
我可以将输出重定向到文件和STDOUT,就像这样
ls /usr/bin | tee foo.txt
Run Code Online (Sandbox Code Playgroud)
但我不能这样做
ls /fake/folder | tee foo.txt || exit 1
Run Code Online (Sandbox Code Playgroud)
因为我得到的输出tee而不是ls
如何将输出重定向到文件和STDOUT 并在出错时退出
这究竟是什么pipefail运行选项适用:
# Make a pipeline successful only if **all** components are successful
set -o pipefail
ls /fake/folder | tee foo.txt || exit 1
Run Code Online (Sandbox Code Playgroud)
如果你想明确优先顺序,那么请考虑:
set -o pipefail
{ ls /fake/folder | tee foo.txt; } || exit 1 # same thing, but maybe more clear
Run Code Online (Sandbox Code Playgroud)
...或者,如果要避免进行运行时配置更改,可以使用PIPESTATUS检查最新管道的任何单个元素的退出状态:
ls /fake/folder | tee foo.txt
(( ${PIPESTATUS[0]} == 0 )) || exit
Run Code Online (Sandbox Code Playgroud)
如果你不想采取任何上述的方法,但都愿意使用bash所采用ksh的扩展,把它在一个替代的过程,而不是一个管道将防止tee从影响退出状态:
ls /fake/folder > >(tee foo.txt) || exit 1
Run Code Online (Sandbox Code Playgroud)