I’m writing a shell script in Python (#!/usr/bin/env python
). I’m a bit new to shell scripting in general, so apologies if I’m misunderstanding something.
My current understanding is that if my shell script works successfully, I should call sys.exit()
to indicate that it’s succeeded (i.e. return 0).
If I’ve encountered an error (specifically, that the user has passed in an argument that I’m not expecting), what should I return, and how?
Is it okay just to call sys.exit()
with any non-zero value, e.g. sys.exit(1)
?
Any non zero value will do. So sys.exit(1)
is correct. These error codes are useful for using scripts on the command line:
python test.py && echo 'success'
The above will not print 'success' when your script returns anything but 0.
Most Shell utilites have various return values depending on the error that occurs.
The standard is when exiting with a status code of 0, it means the execution ended successfully.
For other error codes, this is highly dependant on the utility itself. You're most likely to learn about error codes in the man pages of the aforementioned utilities.
Here's a simple example of the ls
man page:
Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory), 2 if serious trouble (e.g., cannot access command-line argument).
It's highly recommended that you document properly your utility's exit codes in order for its users to use it correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With