0
votes

In My shell scripts1, It works.:

test1.sh

python main.py
if [[ $? -ne 0 ]]
then
exit
fi

test2.sh

python main.py 2>&1 | tee log.txt 
if [[ $? -ne 0 ]]
then
exit
fi

Script 2 is failed. How could I get the return code of python-call main in test2.sh?

3

3 Answers

2
votes

If you use more commands in one line, you need to use the PIPESTATUS to get the proper return code for each command.

For example:

Python code:

import sys


def exit_with_code():
    sys.exit(5)


exit_with_code()

Shell script:

python3 test.py  2>&1 | tee log.txt
echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"

Output:

5 0

It means the return code of Python script is 5 and the return code of tee is 0.

1
votes

You tagged your question for POSIX Shell, and AFIK, there is no way to achieve this in a POSIX Shell. However, many other shells do have a feature, which allow this.

For instance, if you could use bash, you can use PIPESTATUS, as was suggested here already. If you go for Zsh, there is a similar array named pipestatus.

If you want to go for ksh, you don't have an equivalent feature, but here is a discussion how to deal with this problem in Korn Shell.

0
votes

You can do the redirection outside of the if and also avoid the antipattern.

if ! python main.py; then
   exit
fi 2>&1 | tee log.txt

(See Why is testing "$?" to see if a command succeeded or not, an anti-pattern?)