我想在脚本执行之前查明 Mac OS X 计算机上的默认浏览器是否为 Google Chrome。
我该怎么做?谢谢!
您可以
grep/awk
启动服务首选项列表来找出哪个浏览器被设置为默认:
x=~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist; \
plutil -convert xml1 $x; \
grep 'https' -b3 $x | awk 'NR==2 {split($2, arr, "[><]"); print arr[3]}'; \
plutil -convert binary1 $x
这会将变量 (
x
) 设置为启动服务首选项列表,然后使用 plutil
将其转换为 xml
格式,以便我们可以 grep
它。我们找到要查找的字符串 (https
),然后输出结果。最后一步是将 plist 转换回 binary
格式。
如果将 chrome 设置为默认,您将得到:
结果:
com.google.chrome
无需转换,使用此脚本:
plutil -p ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist | grep 'https' -b3 |awk 'NR==3 {split($4, arr, "\""); print arr[2]}'
以下命令将打印
https
的默认应用程序的ID:
defaults read com.apple.LaunchServices/com.apple.launchservices.secure LSHandlers \
| sed -n -e '/LSHandlerURLScheme = https;/{x;p;d;}' -e 's/.*=[^"]"\(.*\)";/\1/g' -e x
如果 Firefox 是您的默认浏览器,您会得到
org.mozilla.firefox
。
该脚本使用
defaults
命令读取相应的系统默认值,并从 https
匹配行的上面一行中提取 ID(更多信息可以在 https://unix.stackexchange.com/questions 中阅读) /206886/print-previous-line-after-a-pattern-match-using-sed)。
您可以在其周围包装一个函数并允许传递方案:
# Returns the default app for the specified scheme (default: https).
default_app() {
local scheme=${1:-https}
defaults read com.apple.LaunchServices/com.apple.launchservices.secure LSHandlers \
| sed -n -e "/LSHandlerURLScheme = $scheme;/{x;p;d;}" -e 's/.*=[^"]"\(.*\)";/\1/g' -e x
}
现在的通话是
default_app
# or
default_app https
我想您也想用 ID 做一些事情。
可以通过
application id
实现与 Apple Script 的集成。
以下 shell 脚本运行一个 Apple 脚本,该脚本激活/聚焦/将您的默认浏览器置于前面:
osascript <<APPLE_SCRIPT
tell application id "$(default_app)"
activate
end tell
APPLE_SCRIPT
与单行相同:
osascript -e "tell application id \"$(default_app)\"" -e 'activate' -e 'end tell'
当前接受的答案将首选项文件之一转换为 XML,然后再转换回二进制,如果中间出现问题,您的文件可能会损坏。
使用
plutil
时转换文件而不修改文件的最佳方法是使用 -o -
选项将输出设置为 STDIN。
如果您安装了
jq
,获取默认浏览器的捆绑包 ID 的更准确方法如下:
plutil \
-convert json -o - \
"$HOME"'/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist' \
| jq -r '.LSHandlers[] | select( .LSHandlerURLScheme=="https" ) | .LSHandlerRoleAll'