Description
Use "0" and "1", for input values, and do string tests:
if [ "${flag:-0}" = "0" ]
if [ "${flag:-0}" != "0" ]
if [ "$?" != "0" ] # this is optional, since $? will always be an int
This is a common typo:
If "flag" is not set, or it is set to a non-integer, the following if stmt fails with a syntax error. If "flag" is not set it would be better if it was assumed to be "false"
if [ $flag -ne 0 ]; then
or this would be safer style (always define a "good" default value), but it will still have a syntax error if flag is not an integer.
if [ ${flag:-1} -ne 0 ]; then
Notice also the style for testing true/false, only "0" or "not 0" is tested. There should be no tests looking for "1" or any other value. Exception handling using error return codes would be the only exception.
A Better Solution
-
Validate ALL of the vars that could be user-settable.
-
Vars that are boolean values could accept, t, f, true, false, yes, no, 0, 1, and a validator would echo "true" or "false" (and return the corresponding codes), throw an error, or use a default value (with a warning). Note: Bash confuses things with return codes that are reversed from the usual 0/1 expectation: 0=OK, true, !0=problem, false.
-
Vars that require specific values or a range of integers could also include some transformations, throw an error, or use a default value (with a warning).