巴什整数比较 [英] Bash integer comparison

查看:160
本文介绍了巴什整数比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这给出了以下错误:

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

推荐答案

本脚本作品!

#/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的逻辑,由于问题是关于计算。这是一个只有算术EX pressions 的:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requiers 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]如果第一个参数是一个字符串

这篇关于巴什整数比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆