Pipe output and capture exit status in Bash

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

    By combining PIPESTATUS[0] and the result of executing the exit command in a subshell, you can directly access the return value of your initial command:

    command | tee ; ( exit ${PIPESTATUS[0]} )

    Here's an example:

    # the "false" shell built-in command returns 1
    false | tee ; ( exit ${PIPESTATUS[0]} )
    echo "return value: $?"
    

    will give you:

    return value: 1

提交回复
热议问题