Pipe output and capture exit status in Bash

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

    Base on @brian-s-wilson 's answer; this bash helper function:

    pipestatus() {
      local S=("${PIPESTATUS[@]}")
    
      if test -n "$*"
      then test "$*" = "${S[*]}"
      else ! [[ "${S[@]}" =~ [^0\ ] ]]
      fi
    }
    

    used thus:

    1: get_bad_things must succeed, but it should produce no output; but we want to see output that it does produce

    get_bad_things | grep '^'
    pipeinfo 0 1 || return
    

    2: all pipeline must succeed

    thing | something -q | thingy
    pipeinfo || return
    

提交回复
热议问题