Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash integer comparison

I want to write a Bash script that checks if there is at least one parameter and if there is one, if that parameter is either a 0 or a 1.

This is the script:

#/bin/bash if (("$#" < 1)) && ( (("$0" != 1)) ||  (("$0" -ne 0q)) ) ; then     echo this script requires a 1 or 0 as first parameter. fi xinput set-prop 12 "Device Enabled" $0 

This gives the following errors:

./setTouchpadEnabled: line 2: ((: ./setTouchpadEnabled != 1: syntax error: operand expected (error token is "./setTouchpadEnabled != 1") ./setTouchpadEnabled: line 2: ((: ./setTouchpadEnabled -ne 0q: syntax error: operand expected (error token is "./setTouchpadEnabled -ne 0q") 

What am I doing wrong?

like image 825
Cheiron Avatar asked Jan 24 '13 21:01

Cheiron


1 Answers

This script works!

#/bin/bash if [[ ( "$#" < 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" $0 fi 

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/bash if (( $# )) && (( $1 == 0 || $1 == 1 )); then     echo "first parameter is $1"     xinput set-prop 12 "Device Enabled" $0 else     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 0 first parameter is 0  $ ./tmp.sh 1 first parameter is 1  $ ./tmp.sh 2 this script requires a 1 or 0 as first parameter. 

[1] the second fails if the first argument is a string

like image 195
user000001 Avatar answered Oct 07 '22 17:10

user000001