Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

Within my shell script I run this command:

python script.py

I was wondering, as a two part question:

  1. How can I program my python script to pass a status back to the shell script that ran it depending on what happens in the python script. For example if something goes wrong in the python script have it exit with a code of 1 which is sent back to shell.

  2. How can I get my shell script to read the exit code of python and exit for an error? For example, a status code of anything but 0 then exit.

share|improve this question
    
For #2: stackoverflow.com/questions/90418/… – acjay Jan 21 '13 at 22:01

1 Answer 1

up vote 10 down vote accepted

First, you can pass the desired exit code as an argument to sys.exit in your python script.

Second, the exit code of the most recently exited process can be found in the bash parameter $?. However, you may not need to check it explicitly:

if python script.py; then
    echo "Exit code of 0, success"
else
    echo "Exit code of $?, failure"
fi

To check the exit code explicitly, you need to supply a conditional expression to the if statement:

python script.py
if [[ $? = 0 ]]; then
    echo "success"
else
    echo "failure: $?"
fi
share|improve this answer
    
Do I need a line before your code saying python script.py to run it? – Jimmy Jan 21 '13 at 22:03
    
Or instead, does your code also run the script as well? – Jimmy Jan 21 '13 at 22:04
    
The list of commands give in the if statement is executed, and its exit code determines which branch of the if is executed next. – chepner Jan 21 '13 at 22:06
    
I don't get how this works. To me this is saying "if script then" do this. Shouldn't it be "if script exit code = 0 then" – Jimmy Jan 21 '13 at 22:15
    
The if statement works a little differently in shell scripts than in other languages, due to their focus on running other programs. I'll update the answer to give an example of checking the exit code explicitly for contrast. – chepner Jan 21 '13 at 22:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.