Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the exit code of a Python script in a Bash script

I'm new to Bash and want to catch my Python script exit code.

My script.py looks like:

#! /usr/bin/python
def foofoo():
    ret = # Do logic
    if ret != 0:
        print repr(ret) + 'number of errors'
        sys.ext(1)
    else:
        print 'NO ERRORS!!!!'
        sys.exit(0)

def main(argv):
    # Do main stuff
    foofoo()

if __main__ == "__main__":
    main(sys.argv[1:]

My Bash script:

#!/bin/bash
python script.py -a a1  -b a2 -c a3
if [ $?!=0 ];
then
    echo "exit 1"
fi
echo "EXIT 0"

My problem is that I am always getting exit 1 printed in my Bash script. How can I get my Python exit code in my Bash script?

like image 631
LordTitiKaka Avatar asked Dec 14 '22 22:12

LordTitiKaka


1 Answers

The spaces are important because they are the arguments delimiter:

if [ $? != 0 ];
then
    echo "exit 1"
fi
echo "EXIT 0"

Or numeric test -ne. See man [ for [ command or man bash for builtin more details.

# Store in a variable. Otherwise, it will be overwritten after the next command
exit_status=$?
if [ "${exit_status}" -ne 0 ];
then
    echo "exit ${exit_status}"
fi
echo "EXIT 0"
like image 148
Nahuel Fouilleul Avatar answered Dec 28 '22 07:12

Nahuel Fouilleul