Pipe output and capture exit status in Bash

后端 未结 15 1413
盖世英雄少女心
盖世英雄少女心 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:33

    There's an array that gives you the exit status of each command in a pipe.

    $ cat x| sed 's///'
    cat: x: No such file or directory
    $ echo $?
    0
    $ cat x| sed 's///'
    cat: x: No such file or directory
    $ echo ${PIPESTATUS[*]}
    1 0
    $ touch x
    $ cat x| sed 's'
    sed: 1: "s": substitute pattern can not be delimited by newline or backslash
    $ echo ${PIPESTATUS[*]}
    0 1
    

提交回复
热议问题