Bash整数比较

时间:2013-01-24 21:39:41

标签: 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

这会出现以下错误:

./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")

我做错了什么?

4 个答案:

答案 0 :(得分:36)

此脚本有效!

#/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

但这也有效,而且还保留了OP的逻辑,因为问题是关于计算。这里只有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

输出相同 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.

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

答案 1 :(得分:11)

更简单的解决方案;

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

<强>输出

$ ./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

<强>解释

  • (( )) - 使用整数计算表达式。
  • ${1:-2} - 如果未定义,则使用参数扩展设置值2
  • >= 2 - 如果整数大于或等于两个2,则为真。

答案 2 :(得分:6)

shell命令的第0个参数是命令本身(有时候是shell本身)。您应该使用$1

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )

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

(( "$#" < 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?

这可能是你想要的:

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

答案 3 :(得分: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