0

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?

milanbalazs
  • 4,811
  • 4
  • 23
  • 45
Donghui Sun
  • 253
  • 1
  • 2
  • 14

3 Answers3

2

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.

milanbalazs
  • 4,811
  • 4
  • 23
  • 45
  • @milanbalazs : PIPESTATUS is not defined in [Posix Shell](https://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html) – user1934428 Aug 29 '19 at 07:22
  • Yes, you are right! But the questioner didn't mentioned POSIX in his question! But this problem can be solved with temp files in POSIX. – milanbalazs Aug 29 '19 at 07:25
  • @milanbalazs: Actually he did. He tagged it as _Shell_, and the definition of this tag says that unless another tag explicitly mentions a specific shell, a POSIX compatible solution is asked for. – user1934428 Aug 30 '19 at 06:53
  • I agree! Sorry, it was my mistake! I will pay more attention to tags. On the other hand, the questioner uses `Bash` so he can use the `PIPESTATUS`! :) – milanbalazs Aug 30 '19 at 06:57
1

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.

user1934428
  • 19,864
  • 7
  • 42
  • 87
0

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?)

tripleee
  • 175,061
  • 34
  • 275
  • 318