Bash integer comparison
This script works!
#/bin/bashif [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then echo this script requires a 1 or 0 as first parameter.else echo "first parameter is $1" xinput set-prop 12 "Device Enabled" $0fi
But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:
#/bin/bashif (( $# )) && (( $1 == 0 || $1 == 1 )); then echo "first parameter is $1" xinput set-prop 12 "Device Enabled" $0else echo this script requires a 1 or 0 as first parameter.fi
The output is the same1:
$ ./tmp.sh this script requires a 1 or 0 as first parameter.$ ./tmp.sh 0first parameter is 0$ ./tmp.sh 1first parameter is 1$ ./tmp.sh 2this script requires a 1 or 0 as first parameter.
[1] the second fails if the first argument is a string
Easier solution;
#/bin/bashif (( ${1:-2} >= 2 )); then echo "First parameter must be 0 or 1"fi# rest of script...
Output
$ ./test First parameter must be 0 or 1$ ./test 0$ ./test 1$ ./test 4First parameter must be 0 or 1$ ./test 2First parameter must be 0 or 1
Explanation
(( ))
- Evaluates the expression using integers.${1:-2}
- Uses parameter expansion to set a value of2
if undefined.>= 2
- True if the integer is greater than or equal to two2
.
The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1
.
(("$#" < 1)) && ( (("$1" != 1)) || (("$1" -ne 0q)) )
Your boolean logic is also a bit confused:
(( "$#" < 1 && # If the number of arguments is less than one… "$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?
This is probably what you want:
(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1