From bd96ee0dfea2d221b5d0acc4df51b0add3925c68 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Sat, 24 Nov 2018 23:04:42 -0800 Subject: [PATCH] Created SC2242 (markdown) --- SC2242.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 SC2242.md diff --git a/SC2242.md b/SC2242.md new file mode 100644 index 0000000..26bef05 --- /dev/null +++ b/SC2242.md @@ -0,0 +1,36 @@ +## Can only exit with status 0-255. Other data should be written to stdout/stderr. + +### Problematic code: + +```sh +exit "Bad filename" +``` + +### Correct code: + +```sh +echo "Bad filename" >&2 +exit 1 +``` + +### Rationale: + +`exit` can only be used to signal success or failure (0 = success, 1-255 = failure). It can not be used to return string data, and it can not be used to print error messages. + +String data should be written stdout, before an `exit 0` to exit with success. + +Errors should instead be written to stderr, with an `exit 1` (or higher) to exit with failure: + +``` +if [ ! -f "$1" ] +then + echo "$1 is not a regular file" >&2 + exit 1 +fi +``` + +Note in particular that `exit -1` is equivalent to `exit 255`, but that `exit 1` is the more canonical way of expressing the first possible error code. + +### Exceptions: + +None \ No newline at end of file