If/else macOS 终端声明

If/else Statement with macOS terminal

所以我是 macOS 终端的新手,我想执行一个简单的命令,如果显示隐藏的 mac 文件夹,隐藏它们并如果它们被隐藏,显示它们。

我主要习惯python所以我的第一反应是:

if defaults write com.apple.finder AppleShowAllFiles is NO: 
    defaults write com.apple.finder AppleShowAllFiles YES 
else: 
    defaults write com.apple.finder AppleShowAllFiles NO

现在我很确定这行不通,但我怎么能在 shell 脚本中实现这样的事情呢?

你可以这样做:

#!/bin/bash

if [ '1' = $(defaults read com.apple.finder AppleShowAllFiles) ]; then
    echo "AppleShowAllFiles is enabled"
elif [ '0' = $(defaults read com.apple.finder AppleShowAllFiles) ];   then
    echo "AppleShowAllFiles is not enabled"
else
    echo "defaults returned some other value"
fi

或者将默认值的 return 值分配给变量:

#!/bin/bash

defaultsReturn=$(defaults read com.apple.finder AppleShowAllFiles)

if [ '1' = "$defaultsReturn" ]; then
    echo "AppleShowAllFiles is enabled"
elif [ '0' = "$defaultsReturn" ]; then
    echo "AppleShowAllFiles is not enabled"
else
    echo "defaults returned some other value: $defaultsReturn"
fi

在终端输入 if then else

if (( 1 == 1));then echo "hi"; fi;