9

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.exit(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?

1 Answer 1

23

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"
Sign up to request clarification or add additional context in comments.

Comments

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.