Pipe output and capture exit status in Bash

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

    PIPESTATUS[@] must be copied to an array immediately after the pipe command returns. Any reads of PIPESTATUS[@] will erase the contents. Copy it to another array if you plan on checking the status of all pipe commands. "$?" is the same value as the last element of "${PIPESTATUS[@]}", and reading it seems to destroy "${PIPESTATUS[@]}", but I haven't absolutely verified this.

    declare -a PSA  
    cmd1 | cmd2 | cmd3  
    PSA=( "${PIPESTATUS[@]}" )
    

    This will not work if the pipe is in a sub-shell. For a solution to that problem,
    see bash pipestatus in backticked command?

提交回复
热议问题