Command [the shell] return pipe connection determination value

Scenes:

In the command execution bash pipe connections you need to be obtained to the respective command values ​​for determining the return

In the script we may need to print the results to the screen, and saved in a file for later analysis, write the following command

1 command 2》&1 | tee out.txt
2 ST=$?

Found that regardless of whether the value of a successful command, ST is 0, how to solve this problem

 

Solution:

1,set -o pipefail

Set pipefail option, so that when the pipe connection command, the command as long as a pipe connection of any return value is not 0, then the whole expression returns the value is not 0

1 (base) $ ls /root 2> /dev/null | ls /home/ &>/dev/null
2 (base) $ echo $?
3 0
4 (base) $ set -o pipefail 
5 (base) $ ls /root 2> /dev/null | ls /home/ &>/dev/null
6 (base) $ echo $?
7 2

In this way can be used in shells

 

2,$PIPESTATUS

Inside the shell variable, $ PIPESTATUS is an array, the number of pipe connections command, $ PIPESTATUS contains how many values 

1 (base) $ ls /root 2> /dev/null | ls /home/ &>/dev/null
2 (base) $ echo ${PIPESTATUS[@]}
3 2 0

The return command needs to be acquired at the value corresponding to the return value to get

This only take effect in bash, zsh or another shell may be different

 

Guess you like

Origin www.cnblogs.com/liawne/p/11584059.html