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

I am writing a rather trivial bash script; if I find an error (not with a bad exit status from any other process), I want to exit the exit status indicating an error (without being too specific).

It seems that I should do exit 1 (for example, TLDP Advanced bash scripting guide , and the standard C library stdlib.h ); but I notice a lot of people exit -1 . Why is this?

+5
source share
1 answer

TLDP ABS has a dubious legal force (in that it often uses, without comment, sub-pair practices), so I would not perceive this as a concrete bastion of correctness about it.

Thus, valid return codes are between 0 and 255 , and 0 is success. So yes, 1 is a perfectly valid (and general) error code.

Obviously, I canโ€™t say for sure why other people do this, but I have two thoughts on this topic.

  • Inability to switch context (possibly in combination with a lack of domain knowledge).

    In many languages, the return value of -1 from a function is a valid value and stands out from all positive values โ€‹โ€‹that can (as expected) return normally.

    Thus, an attempt to extend this template (which the author takes over time) into the script / etc shell. for them a reasonable thing. Especially if they do not have domain knowledge to understand that valid return codes are between 0 255 .

  • An attempt to disable these lines of failure to โ€œstand outโ€ from normal exit cases (which may or may not be successful exits themselves) in an attempt to visually distinguish a specific set of extremely unlikely or unusual exit cases.

    Exiting -1 really works, it just doesn't give you a return code of -1 , it gets a return code of 255 . (Try (exit -1); echo $? In your shell to see this.) Thus, this is not an entirely unreasonable thing to do (although it is confusing and involved in the confusion regarding exit codes).

+5
source

Source: https://habr.com/ru/post/1233716/


All Articles