您好,我有以下脚本:
#! /bin/bash
Output=$(defaults read com.apple.systemuiserver menuExtras | grep Bluetooth.menu)
Check="\"/System/Library/CoreServices/Menu Extras/Bluetooth.menu\","
echo $Output
echo $Check
if [ "$Output" = "$Check" ]
then
echo "OK"
else
echo "FALSE"
echo "Security Compliance Setting 'Show Bluetooth Status in Menu Bar(2.1.3)' has been changed!" | logger
fi
当您运行它时,两个变量都具有完全相同的输出,但是检查总是说它是FALSE
这是我终端的输出:
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
FALSE
知道为什么没有检测到它们相同吗?
正如评论中的每个人所怀疑的那样,问题出在$ Output(将其echo $Output
删除)中的空格。具体来说,是4个前导空格(请注意,在下面的命令行中,“ $”是我的shell提示):
$ defaults read com.apple.systemuiserver menuExtras | grep Bluetooth.menu
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
$ Output=$(defaults read com.apple.systemuiserver menuExtras | grep Bluetooth.menu)
$ echo $Output
"/System/Library/CoreServices/Menu Extras/Bluetooth.menu",
$ echo "[$Output]"
[ "/System/Library/CoreServices/Menu Extras/Bluetooth.menu",]
$ Check=" \"/System/Library/CoreServices/Menu Extras/Bluetooth.menu\","
$ if [ "$Output" = "$Check" ]; then echo "OK"; else echo "FALSE"; fi
OK
请注意,由于空格数量可能并不总是相同,因此在[[ ]]
条件表达式中使用bash的通配符匹配功能可能会更安全(这不适用于[ ]
):
$ Check="\"/System/Library/CoreServices/Menu Extras/Bluetooth.menu\","
$ if [[ "$Output" = *"$Check" ]]; then echo "OK"; else echo "FALSE"; fi
OK
您也可以完全跳过字符串比较,而仅使用以下事实:grep
仅在找到匹配项时返回成功状态:
#!/bin/bash
if defaults read com.apple.systemuiserver menuExtras | grep -q "/System/Library/CoreServices/Menu Extras/Bluetooth.menu"; then
echo "OK"
else
echo "FALSE"
echo "Security Compliance Setting 'Show Bluetooth Status in Menu Bar(2.1.3)' has been changed!" | logger
fi
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句