Bash整数比较

Che*_*ron 40 bash comparison integer

我想写一个bash脚本,检查是否至少有一个参数,如果有一个参数,如果该参数是0或1.这是脚本:

#/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
Run Code Online (Sandbox Code Playgroud)

这会出现以下错误:

./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")
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

use*_*001 40

这个脚本有效!

#/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
Run Code Online (Sandbox Code Playgroud)

但这也有效,并且另外保留了OP的逻辑,因为问题是关于计算.这里只有算术表达式:

#/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
Run Code Online (Sandbox Code Playgroud)

输出相同1:

$ ./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.
Run Code Online (Sandbox Code Playgroud)

[1]如果第一个参数是一个字符串,则第二个失败


koo*_*ola 12

更简单的解决方案

#/bin/bash
if (( ${1:-2} >= 2 )); then
    echo "First parameter must be 0 or 1"
fi
# rest of script...
Run Code Online (Sandbox Code Playgroud)

产量

$ ./test 
First parameter must be 0 or 1
$ ./test 0
$ ./test 1
$ ./test 4
First parameter must be 0 or 1
$ ./test 2
First parameter must be 0 or 1
Run Code Online (Sandbox Code Playgroud)

说明

  • (( )) - 使用整数计算表达式.
  • ${1:-2}- 使用参数扩展来设置2if undefined 的值.
  • >= 2- 如果整数大于或等于2,则为真2.


koj*_*iro 7

shell命令的第0个参数是命令本身(或者有时是shell本身).你应该使用$1.

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )
Run Code Online (Sandbox Code Playgroud)

你的布尔逻辑也有点困惑:

(( "$#" < 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?
Run Code Online (Sandbox Code Playgroud)

这可能是你想要的:

(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1
Run Code Online (Sandbox Code Playgroud)


Wil*_*iam 5

我知道这已经得到了解答,但这只是因为我认为案例是一种不被重视的工具.(也许是因为人们认为它很慢,但它至少和if一样快,有时候更快.)

case "$1" in
    0|1) xinput set-prop 12 "Device Enabled" $1 ;;
      *) echo "This script requires a 1 or 0 as first parameter." ;;
esac
Run Code Online (Sandbox Code Playgroud)