Bash integer comparison

后端 未结 4 1389
半阙折子戏
半阙折子戏 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:18

    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
    

提交回复
热议问题