Pipe output and capture exit status in Bash

后端 未结 15 1093
盖世英雄少女心
盖世英雄少女心 2020-11-22 08:07

I want to execute a long running command in Bash, and both capture its exit status, and tee its output.

So I do this:

command | tee out.txt
ST=$?


        
相关标签:
15条回答
  • 2020-11-22 08:37

    Dumb solution: Connecting them through a named pipe (mkfifo). Then the command can be run second.

     mkfifo pipe
     tee out.txt < pipe &
     command > pipe
     echo $?
    
    0 讨论(0)
  • 2020-11-22 08:41

    There is an internal Bash variable called $PIPESTATUS; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.

    <command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0
    

    Or another alternative which also works with other shells (like zsh) would be to enable pipefail:

    set -o pipefail
    ...
    

    The first option does not work with zsh due to a little bit different syntax.

    0 讨论(0)
  • 2020-11-22 08:42

    In Ubuntu and Debian, you can apt-get install moreutils. This contains a utility called mispipe that returns the exit status of the first command in the pipe.

    0 讨论(0)
提交回复
热议问题