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?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Matts
  • 1,301
  • 11
  • 30
  • As an aside, your original code is just a pretzel way of writing `Python script.py > /logfile.log 2>&1 || exit`. See https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern - and probably you can easily get rid of the `Python` before the script name by putting a correct shebang. – tripleee Aug 04 '19 at 09:29
  • @tripleee I tried the command, and it exited with code 1, and logged to file, but didn't output to the screen. – Matts Aug 04 '19 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. – tripleee Aug 04 '19 at 12:52

1 Answers1

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

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 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)? – Mihir Luthra Aug 04 '19 at 09:22
  • I suggest to start a new question. – Cyrus Aug 04 '19 at 09:25
  • https://stackoverflow.com/questions/57345485/is-pipestatus-of-processes-running-in-background-trackable – Mihir Luthra Aug 04 '19 at 09:40