19

I am calling a python script from within a shell script. The python script returns error codes in case of failures.

How do I handle these error codes in shell script and exit it when necessary?

anishsane
  • 20,270
  • 5
  • 40
  • 73
SpikETidE
  • 6,711
  • 15
  • 46
  • 62

3 Answers3

34

The exit code of last command is contained in $?.

Use below pseudo code:

python myPythonScript.py
ret=$?
if [ $ret -ne 0 ]; then
     #Handle failure
     #exit if required
fi
anishsane
  • 20,270
  • 5
  • 40
  • 73
  • 5
    Don't do this. Just use `if python myPythonScript.py; then ... fi` or `python myPythonScript.py || ...` – Josh Cartwright Jan 10 '13 at 14:29
  • 9
    Hmm... with my approach, you can choose different error handlers with different exit code values. e.g. you may want to ignore some trivial errors codes. Your approach however, is still technically correct for his requirement. – anishsane Jan 10 '13 at 15:33
  • 6
    This simply does not work for me. Bash has `$?` as 0 even though my python script exits with `sys.exit(1)` – tadasajon Jun 19 '17 at 17:14
4

You mean the $? variable?

$ python -c 'import foobar' > /dev/null
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named foobar
$ echo $?
1
$ python -c 'import this' > /dev/null
$ echo $?
0
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
3

Please use logic below to process script execution result:

python myPythonScript.py
# $? =  is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. 
if [ $? -eq 0 ]
then
  echo "Successfully executed script"
else
  # Redirect stdout from echo command to stderr.
  echo "Script exited with error." >&2
fi
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • is it possible to wait for python script to complete before executing shell commands after that – dev Apr 29 '20 at 05:24
  • the if on line 3 will be tested after script completes execution, but it's still depends on script which you have it may spin of worker and exit with positive status, you can try to create separate question for that with script attached. – Andriy Ivaneyko Apr 29 '20 at 07:56