如何在 linux(真或假)bash 命令上设置切换?

How to set a toggle on linux (True or False) bash command?

我目前指定了我的 thinkvantage 按钮来关闭点击我的触控板,但我想将其转换为切换 on/off 开关。

目前,这是我用来关闭它(或使用 CTRL 打开)的 bash 命令:

gsettings set org.gnome.settings-daemon.peripherals.touchpad tap-to-click true
gsettings set org.gnome.settings-daemon.peripherals.touchpad tap-to-click false

换句话说,如何将其变成条件切换开关 bash 语句?

大概是这样的:

#!/bin/bash
class=org.gnome.settings-daemon.peripherals.touchpad
name=tap-to-click
status=$(gsettings get "$class" "$name")
status=${status,,} # normalize to lower case; this is a modern bash extension
if [[ $status = true ]]; then
  new_status=false
else
  new_status=true
fi
gsettings set "$class" "$name" "$new_status"

分解成碎片:

  • #!/bin/bash 确保此脚本的解释器是 bash,启用扩展语法,例如 [[ ]].
  • 语法$( )是"command substitution";这将运行一个命令,并替换该命令的输出。因此,如果输出为 true,则 status=$(...) 变为 status=true.
  • 参数扩展 ${name,,} 扩展 name 的内容,同时将这些内容转换为全小写,并且仅在较新版本的 bash 中可用。如果您想支持 /bin/sh 或更早版本的 bash,请考虑使用 status=$(printf '%s\n' "$status" | tr '[:upper:]' '[:lower:]'),或者如果 gsettings get 的输出总是小写,则只删除此行。
  • 比较 [[ $status = true ]] 依赖于 bash 扩展 [[ ]](在其他现代 ksh 派生的 shell 中也可用)以避免引用的需要。如果您希望它与 #!/bin/sh 一起使用,则应改用 [ "$status" = true ]。 (请注意,==[[ ]] 内部是允许的,但在 [ ] 内部 POSIX shell 上 不允许 ;这就是为什么最好不要养成使用的习惯。

请注意空格在 bash 中很重要! foo = barfoo= barfoo=bar 是完全不同的语句,它们三个做的事情与另外两个不同。一定要认识到从这个例子中复制的不同之处。

在 Ubuntu Unity 时钟上切换秒数(可直接粘贴为键绑定命令):

bash -c 'gsettings set com.canonical.indicator.datetime show-seconds $(gsettings get com.canonical.indicator.datetime show-seconds | perl -neprint/true/?false:true)'

对于 GNOME:

bash -c 'gsettings set org.gnome.desktop.interface clock-show-seconds $(gsettings get org.gnome.desktop.interface clock-show-seconds | perl -neprint/true/?false:true)'

来源:https://www.commandlinefu.com/commands/view/24256/toggle-the-touchpad-on-or-off

synclient TouchpadOff=$(synclient -l | grep -q 'TouchpadOff.*1'; echo $?)

tp=$(synclient -l | grep TouchpadOff | awk '{ print  }') && tp=$((tp==0)) && synclient TouchpadOff=$tp