Capturing a program’s exit status in a Bash script

Use of a Bash script to capture an exit status in a Python program. Would also work for a C/C++, Java, or any program that can exit with an exit status. Useful for running batch jobs in a scheduler program like IBM’s Workload Scheduler(formerly known as Tivoli Maestro).

Python program is shown first. Simple program that allows you to input the exit status.

import sys

#ask for integer for exit status. Other than 0 will be error
exit_status = int(input("\nInput an integer to exit with: "))

#exit with error status
sys.exit(exit_status)

Bash script to run the Python program and capture the exit status.

#!/bin/bash
printf "\n$0\n"
cd `dirname $0`
pwd

printf "\n$(date)\n"

#run python program
python3 error.py

#capture exit from python program
err=$?

printf "\nExit status:\n$err\n"

#if exit status not zero, then exit Bash script with error status
if [[ $err -ne 0 ]]
then
   printf "\nAn error occurred! Exiting!\n\n"
   exit $err 
else
   printf "\nNo error occurred!\n\n"
fi

printf "\n$(date)\n"

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *