Bash integer comparison

后端 未结 4 1408
半阙折子戏
半阙折子戏 2021-01-01 08:45

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:



        
4条回答
  •  春和景丽
    2021-01-01 09:11

    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

提交回复
热议问题