(疾病)論理的な声明

(疾病)論理的な声明

コンピュータ画面を裏返す簡単なスクリプトを作成しようとしています。最初のif文は完全に実行されますが、それ以降$istouchが "on"であると仮定すると、elifブロックは実行されません!失敗せずに-uオプションを使用してbashを実行し、チェックを切り替えようとしましたが、何も機能しませんでした。

#!/bin/bash
xsetwacom --set 16 touch False
istouch='xsetwacom --get 15 touch'
$istouch
if [ "$istouch"=="off" ]
then
    xrandr -o inverted
    xinput set-prop 13 'Coordinate Transformation Matrix' -1 0 1 0 -1 1 0 0 1
    xinput set-prop 15 'Coordinate Transformation Matrix' -1 0 1 0 -1 1 0 0 1
    xinput set-prop 16 'Coordinate Transformation Matrix' -1 0 1 0 -1 1 0 0 1
    xsetwacom --set 15 touch True

elif [ "$istouch"=="on" ]
then
    xrandr -o 0
    xinput set-prop 13 'Coordinate Transformation Matrix' 1 0 0 0 1 0 0 0 1
    xinput set-prop 15 'Coordinate Transformation Matrix' 1 0 0 0 1 0 0 0 1
    xinput set-prop 16 'Coordinate Transformation Matrix' 1 0 0 0 1 0 0 0 1
    xsetwacom --set 15 touch False
fi

ベストアンサー1

あなたのif声明はあなたが思ったように進まなかった。このコマンドを含むBashスクリプトのデバッグをオンにしてから、を使用してオフにすることがset -xできますset +x

はい

したがって、まず、次のようにデバッグを追加します。

#!/bin/bash

## DEBUG
set -x
xsetwacom --set 16 touch False
....

次にスクリプトを実行し、ex.bash次のように呼び出します。

$ ./ex.bash

Bashは次の行を実行しようとします。

if [ "$istouch"=="off" ]

出力でBashが混乱していることがわかります。文字列で動作します'xsetwacom --get 15 touch==off'

+ '[' 'xsetwacom --get 15 touch==off' ']'

議論は==このように扱ってはいけません。 Bashは、そのようなものについて難しいと悪名高い。したがって、次のように前後にスペースを入れます。

 if [ "$istouch" == "off" ]
 elif [ "$istouch" == "on" ]

今少し良く見えます。

+ '[' 'xsetwacom --get 15 touch' == off ']'
+ '[' 'xsetwacom --get 15 touch' == on ']'

ただし、Stirng s を比較したくなく、$istouchその文字列で表されるコマンドの結果を比較したいので、スクリプトの上部を次のように変更します。

....
xsetwacom --set 16 touch False
istouch=$(xsetwacom --get 15 touch)
if [ "$istouch" == "off" ]
....

今コマンドを実行し、xsetwacom結果を$istouch。このデバイスがないため、に関するメッセージを受け取りましたdevice 15。しかし、今スクリプトが行うことは次のとおりです。

++ xsetwacom --get 15 touch
+ istouch='Cannot find device '\''15'\''.'
+ '[' 'Cannot find device '\''15'\''.' == off ']'
+ '[' 'Cannot find device '\''15'\''.' == on ']'

これにより、以下についての洞察を得ることができることを願っています。

  1. スクリプトをデバッグする方法
  2. Bashの構文をよりよく理解する

if文の詳細

このステートメントが正確に一致する理由が疑問に思うかもしれませんif。問題は、[コマンドに単一の文字列を提供する場合、その文字列が空でない場合はこれを事実として扱い、if文がそのセクションにthen属することです。

はい

$ [ "no"=="yes" ] && echo "they match"
they match

$ [ "notheydont"=="yes" ] && echo "they match"
they match

ここで平等検査が行われているように見えますが、そうではありません。[ some-string ]ええ[ -n some-string ]、これはテストです。一部の文字列[n]空です。set -xこれは次のように表示されます。

$ set -x; [ "notheydont"=="yes" ] && echo "they match"; set +x
+ '[' notheydont==yes ']'
+ echo 'they match'
they match
+ set +x

同等性検査パラメーターの間にスペースを入れると、次のようになります。

# fails
$ set -x; [ "notheydont" == "yes" ] && echo "they match"; set +x
+ '[' notheydont == yes ']'
+ set +x

# passes
$ set -x; [ "yes" == "yes" ] && echo "they match"; set +x
+ set -x
+ '[' yes == yes ']'
+ echo 'they match'
they match
+ set +x

今期待通りに動作します!

おすすめ記事