From b9b0bb7584eb80ee5e2c181cd4d0ed62887144a6 Mon Sep 17 00:00:00 2001 From: koalaman Date: Wed, 20 Jan 2016 10:55:23 -0800 Subject: [PATCH] Created SC2056 (markdown) --- SC2056.md | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 SC2056.md diff --git a/SC2056.md b/SC2056.md new file mode 100644 index 0000000..4b013db --- /dev/null +++ b/SC2056.md @@ -0,0 +1,41 @@ +## You probably wanted && here + +### Problematic code: + +```sh +if (( $1 != 0 || $1 != 3 )) +then + echo "$1 is not 0 or 3" +fi +``` + +### Correct code: + +```sh +if (( $1 != 0 && $1 != 3 )) +then + echo "$1 is not 0 or 3" +fi +``` + +### Rationale: + +This is not a bash issue, but a simple, common logical mistake applicable to all languages. + +`(( $1 != 0 || $1 != 3 ))` is always true: + +* If `$1 = 0` then `$1 != 3` is true, so the statement is true. +* If `$1 = 3` then `$1 != 0` is true, so the statement is true. +* If `$1 = 42` then `$1 != 0` is true, so the statement is true. + +`(( $1 != 0 && $1 != 3 ))` is true only when `$1` is not `0` and not `3`: + +* If `$1 = 0`, then `$1 != 3` is false, so the statement is false. +* If `$1 = 3`, then `$1 != 0` is false, so the statement is false. +* If `$1 = 42`, then both `$1 != 0` and `$1 != 3` is true, so the statement is true. + +This statement is identical to `! (( $1 == 0 || $1 == 3 ))`, which also works correctly. + +### Exceptions + +None.