pythonshellreturn-code

How to get retune code of function when using log redirection in Shell?


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?


Solution

  • 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.