1

I'm trying to combine 2 lines that work separately, but I can't get them to work together. To capture and exit code of 1:

Python script.py > /logfile.log 2>&1
ret=$?
if [ $ret -ne 0 ]; then
     exit $ret
fi

To output the result of the script to the screen and a log file:

Python script.py 2>&1 | tee /logfile.log 

I want to combine these 2 commands so that the script will output to the screen and log file, and will also catch the exit code of 1 to abort the script when it fails. I tried combining them in different ways, but the script either continues running, or nothing is output to the screen. Is it possible to do this?

3
  • As an aside, your original code is just a pretzel way of writing Python script.py > /logfile.log 2>&1 || exit. See stackoverflow.com/questions/36313216/… - and probably you can easily get rid of the Python before the script name by putting a correct shebang. Commented Aug 4, 2019 at 9:29
  • @tripleee I tried the command, and it exited with code 1, and logged to file, but didn't output to the screen. Commented Aug 4, 2019 at 12:47
  • Indeed, I am pointing out an error in your original command, not trying to answer your question about how to make it do that. Commented Aug 4, 2019 at 12:52

1 Answer 1

2

Use array PIPESTATUS:

Python script.py 2>&1 | tee /logfile.log
ret="${PIPESTATUS[0]}"
if [[ "$ret" -ne "0" ]]; then
  exit "$ret"
fi

From man bash:

PIPESTATUS: An array variable (see Arrays below) containing a list of exit status values from the processes in the most- recently-executed foreground pipeline (which may contain only a single command).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks the answer helped me aswell. I wanted to ask if I run a script similar to the one above in background is there any way to track its PIPESTATUS(like it mentions to track only recently executed foreground or maybe I misunderstood)?
I suggest to start a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.