Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash Script – If Pyscript Returns Non-zero, Write Errors to Output File AND Quite Bash Script

Have the below in a bash script –

python3 run_tests.py 2>&1 | tee tests.log

If I run python3 run_tests.py alone, I can do the below to exit the script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

python3 run_tests.py

if [ $? -ne 0 ]; then 
   echo 'ERROR: pytest failed, exiting ...'
   exit $?

However, the above working code doesn’t write the output of pytest to a file.

When I run python3 run_tests.py 2>&1 | tee tests.log, the output of pytest will output to the file, but this always returns status 0, since the output job successfully ran.

I need a way to somehow capture the returned code of the python script tests prior to writing to the file. Either that, or something that accomplishes the same end result of quitting the job if a test fails while also getting the failures in the output file.

Any help would be appreciated! 🙂

>Solution :

The exit status of a pipeline is the status of the last command, so $? is the status of tee, not pytest.

In bash you can use the $PIPESTATUS array to get the status of each command in the pipeline.

python3 run_tests.py 2>&1 | tee tests.log
status=${PIPESTATUS[0]} # status of run_tests.py
if [ $status -ne 0 ]; then
    echo 'ERROR: pytest failed, exiting ...'
    exit $status
fi

Note that you need to save the status in another variable, because $? and $PIPESTATUS are updated after each command.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading