In terminal based scripts (Shell, Bash, Python, etc), if you prompt the user “Do you wish to continue?” and the user chooses “No”, what exit code should the script ideally return?
On one hand, the script executed as the user expected it to (the user wanted to quit, so it quit), so it should give an exit code of 0
. On the other hand, the script was unable to complete its main task, which should be a non-zero exit code.
5
There is no real standard on this, other than “zero means keep going”.
So it depends on what should typically happen in a situation where you do this:
$ your-script && do-something-else
…and the user cancels out in your-script
. Is the desired behavior to skip that step and continue (i.o.w., is your-script
completely optional)? Then a zero exit code is appropriate. But if, typically, continuing after the user has cancelled your script is inappropriate, then you should return non-zero. If in doubt, use non-zero: otherwise whoever calls your script won’t be able to distinguish between “user cancelled out” and “user said yes and everything worked as intended” – discarding a non-zero exit code is easy, but figuring out what happened if the code is zero either way is not.
Just make sure that you use distinct exit codes for “user cancelled out” and “something went horribly wrong”, and of course document them.
The script was able to complete its main task: respond without any error to the user. It’s not like it had a permission issue, a segfault, a missing file, or something like this. It was the intended behavior to stop.
Errors should be used when unintended behaviors happen: the user wanted the program to do a task, and the program couldn’t.
4