【问题标题】:How to redirect output to file and STDOUT and exit on error如何将输出重定向到文件和 STDOUT 并在错误时退出
【发布时间】:2018-02-23 00:46:20
【问题描述】:

我可以像这样在出错时退出程序

ls /fake/folder || exit 1

我可以像这样将输出重定向到文件和 STDOUT

ls /usr/bin | tee foo.txt

但我做不到

ls /fake/folder | tee foo.txt || exit 1

因为我得到的是tee 而不是ls 的输出

如何将输出重定向到文件和 STDOUT 和出错时退出

【问题讨论】:

    标签: bash shell pipe stdout


    【解决方案1】:

    这正是pipefail 运行时选项的用途:

    # Make a pipeline successful only if **all** components are successful
    set -o pipefail
    ls /fake/folder | tee foo.txt || exit 1
    

    如果您想明确优先级,顺便说一下,请考虑:

    set -o pipefail
    { ls /fake/folder | tee foo.txt; } || exit 1  # same thing, but maybe more clear
    

    ...或者,如果您想避免更改运行时配置,可以使用PIPESTATUS 检查最近管道的任何单个元素的退出状态:

    ls /fake/folder | tee foo.txt
    (( ${PIPESTATUS[0]} == 0 )) || exit
    

    如果您不想采用上述任何方法,但愿意使用 bash 采用的 ksh 扩展,则将其置于进程替换而不是管道中将阻止 tee从影响退出状态:

    ls /fake/folder > >(tee foo.txt) || exit 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 2014-07-22
      • 2010-09-29
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多