2013-01-24 101 views
32

我想要寫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") 

我在做什麼錯?

+0

看起來你正在使用'SH運行腳本。/ setTouchpadEnabled',而不是使用bash。 – jordanm

+0

@jordanm你是指在shebang線缺乏爆炸? – Kev

回答

32

這個腳本作品!

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

的輸出是相同的:

$ ./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]如果第一參數是字符串第二失敗

+0

非常感謝,錯誤是因爲該命令是xinput而不是輸入 – Cheiron

+0

任何特定的原因,你不堅持在問題中使用的算術表達式?即使用'(('和'))''。 – 0xC0000022L

+1

@ user828193:很明顯,這是關於計算的,所以算術表達式是*要走的路。這就是爲什麼我在你的答案中發現你改變了這個問題的原因。 – 0xC0000022L

5

shell命令的第零個參數是命令本身(或有時是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 
+0

這是一個改進,謝謝。但它仍然給我錯誤: ./setTouchpadEnabled:第2行:((:!= 1:語法錯誤:操作數預期(錯誤標記爲「!= 1」) ./setTouchpadEnabled:第2行:((: 0:語法錯誤:期望的操作數(錯誤標記爲「!= 0」) – Cheiron

+1

引號不是必須在(())裏面,但是它們使得StackOverflow的高亮顯得更加智能 – kojiro

+0

刪除引號給出了相同的錯誤,不幸的是, – Cheiron

10

更簡單的解決方案

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

我知道這已被回答,但這是我的,因爲我認爲案件是一個欠缺評價的工具。 (也許是因爲人們認爲它是緩慢的,但它至少一樣快的,如果,有時會更快。)

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