bash if 語句不斷將第二個參數變更為文字字串

bash if 語句不斷將第二個參數變更為文字字串

所以我不確定它為什麼要這樣做。我的 if 語句不斷將第二個變數解釋為文字字串而不是變數。下面是我的確切程式碼。

lights() {
  bulb1state=$(gatttool -b D8:6F:4B:09:AC:E6 --char-read -a 0x001b)
  echo $bulb1state
  bulb2state=$(gatttool -b DA:5A:4B:09:AC:E6 --char-read -a 0x001b)
  bulb3state=$(gatttool -b AC:E6:4B:07:39:E9 --char-read -a 0x0018)
  bulb4state=$(gatttool -b AC:E6:4B:08:40:50 --char-read -a 0x0018)
  offstate="Characteristic value/descriptor: 00 00 00 00"
  echo $bulb1state
  echo $offstate
  if [ "$offstate" = "$bulb1state" ]; then
    echo $bulb1state
    echo "bulb1 state = off"
    gatttool -b D8:6F:4B:09:AC:E6 --char-write -a 0x001b -n ff000000
    gatttool -b DA:5A:4B:09:AC:E6 --char-write -a 0x001b -n ff000000
    gatttool -b AC:E6:4B:07:39:E9 --char-write -a 0x0018 -n ff000000
    gatttool -b AC:E6:4B:08:40:50 --char-write -a 0x0018 -n ff000000
  fi
}  

我的輸出:

>lights
Characteristic value/descriptor: 00 00 00 00
Characteristic value/descriptor: 00 00 00 00
Characteristic value/descriptor: 00 00 00 00

我不明白為什麼最後 2 個 echo 語句沒有顯示。

編輯:bulb1state 上有一個空白區域。這足以讓我找到解決方法,但我仍然很好奇為什麼當我使用“=”運算符而不是“-eq”運算符時,if 語句的第二項被解釋為文字字串。哪個變數是第一個或第二個也不重要。

答案1

gatttool就像我評論的那樣, (ie )的輸出中可能有額外的空格$bulb1state。對於比較,您應該使用=or ==(它們是等效的),對於數字-eq,請參見這個答案。若要忽略多餘的空格,您可以執行以下操作(請參閱這個答案):

if [[ "$bulb1state" = "$offstate"* ]]; then
  #...
fi

相關內容