Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do some people exit -1 rather than exit 1 on error?

I'm writing a rather trivial bash script; if I detect an error (not with a bad exit status from some other process) I want to exit with an exit status indicating an error (without being too specific).

It seems like I should be doing exit 1 (e.g. as per the TLDP Advanced Bash Scripting Guide, and the C Standard Library's stdlib.h header); yet I notice many people exit -1. Why is that?

like image 928
einpoklum Avatar asked Oct 14 '15 15:10

einpoklum


1 Answers

TLDP's ABS is of questionable validity (in that it often uses, without comment, sub-par practices) so I wouldn't take it as a particular bastion of correctness about this.

That said valid command return codes are between 0 and 255 with 0 being "success". So yes, 1 is a perfectly valid (and common) error code.

Obviously I cannot say for certain why other people do that but I have two thoughts on the topic.

  1. A failure to context switch (possibly combined with a lack of domain knowledge).

    In many languages a return value of -1 from a function is a perfectly valid value and stands out from all the positive values that might (one assumes) normally be returned.

    So attempting to extend that pattern (which the writer has picked up over time) to a shell script/etc. is a reasonable thing for them to do. Especially if they don't have the domain knowledge to realize that valid return codes are between 0 255.

  2. An attempt to have those error exit lines "stand out" from normal exit cases (which may or may not be successful exits themselves) in an attempt to visually distinguish a certain set of extremely unlikely or otherwise extraordinary exit cases.

    An exit of -1 does, actually, work it just doesn't get you a return code of -1 it gets you a return code of 255. (Try (exit -1); echo $? in your shell to see that.) So this isn't an entirely unreasonable thing to want to do (despite being confusing and complicit in perpetrating a confusion about exit codes).

like image 155
Etan Reisner Avatar answered Sep 25 '22 16:09

Etan Reisner