首页 > 解决方案 > 如何在 shell 脚本中为布尔变量编写 if then?

问题描述

我正在尝试编写一个简单的 shell 脚本来隐藏/显示我的桌面图标,但是当我尝试运行它时出现错误“hidedesktopicons.sh: line 1: [[gsettings: command not found”?

我搜索了如何在 shell 脚本中使用 if then 语句。我加了“fi”

enter code here

cat hidedesktopicons.sh 
if [[gsettings get org.mate.background show-desktop-icons = true]]
then gsettings set org.mate.background show-desktop-icons false
else gsettings set org.mate.background show-desktop-icons true
fi

我希望图标隐藏/取消隐藏。我收到错误“hidedesktopicons.sh: line 1: [[gsettings: command not found”

标签: bashshell

解决方案


最直接的问题是你需要空格之后[[

if [[ gsettings ...

一个问题是您需要使用命令替换来捕获的输出,gsettings以便您可以将其与true

if [[ $(gsettings get org.mate.background show-desktop-icons) = true ]]
then gsettings set org.mate.background show-desktop-icons false
else gsettings set org.mate.background show-desktop-icons true
fi

您可能希望定义一对函数来减少此代码的一些重复性:

get_icon_status () {
  gsettings get org.mate.background show-desktop-icons
}

set_icon_status () {
  gsettings set org.mate.background show-desktop-icons "$1"
}

if [[ $(get_icon_status) = true ]]; then
  set_icon_status false
else
  set_icon_status true
fi

推荐阅读