Linux 如果[";$state";==1]。。。永远不等于1

Linux 如果[";$state";==1]。。。永远不等于1,linux,bash,shell,Linux,Bash,Shell,我正在尝试为我的触摸板编写一个切换脚本,稍后我将绑定到一个按键组合,不幸的是,我无法让脚本正常工作。我假设我的变量被声明为错误的或其他什么,但如果有人能为我指出,我会非常感激。我的设备列为: ETPS/2 Elantech Touchpad id=13 [slave pointer (2)] 以下是我目前的脚本: #!/bin/bash device="13" state='xinput list-props '$device' | grep -i "d

我正在尝试为我的触摸板编写一个切换脚本,稍后我将绑定到一个按键组合,不幸的是,我无法让脚本正常工作。我假设我的变量被声明为错误的或其他什么,但如果有人能为我指出,我会非常感激。我的设备列为:

ETPS/2 Elantech Touchpad               id=13    [slave  pointer  (2)]
以下是我目前的脚本:

#!/bin/bash

device="13"
state='xinput list-props '$device' | grep -i "device enabled" | grep -o "[01]$"'

if [ "$state" == 1 ]; then
    xinput disable $device
else
    xinput enable $device
fi
if语句似乎没有按我的预期方式工作,它永远不会等于1,而不是使用:

state='xinput list-props '$device' | grep -i "device enabled" | grep -o "[01]$"'
使用:


小心。

除非您稍后要使用
状态
,否则只需执行以下操作:

if xinput list-props "$device" | grep -i "device enabled" | grep -q -o '1$'; then
   xinput disable "$device"
else
   xinput enable "$device"
fi

你忘了在你的补丁中修复
“$device”
,我的补丁坏了,修复了。谢谢fghj。真不敢相信我把“和”的符号弄混了。我不得不将$device的引号从“$device”改为“$device”,但现在一切正常。非常感谢:)使用
$()
比使用反勾号更好——如果您需要嵌套它们或包含文字双引号,则不会出现令人惊讶的行为。因此:
state=$(xinput-list-props…
同样,
$()
更难与常规单引号混淆。仅供参考--
=
不保证在所有符合POSIX的shell中都能在
[]
内部工作;标准化字符串比较运算符为
=
。并引用您的扩展:
xinput禁用“$device”
;有关自动反馈,请参阅。对于所有您不确定的测试,您可以简单地将set-xv放在脚本的开头,以查看在测试之前实际设置的值。
if xinput list-props "$device" | grep -i "device enabled" | grep -q -o '1$'; then
   xinput disable "$device"
else
   xinput enable "$device"
fi