我想在脚本执行前确定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
格式。结果:
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 Script:
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'
plutil
时,将输出设置为STDIN并使用-o -
选项是在不修改文件的情况下转换文件的最佳方法。jq
,获取默认浏览器的捆绑标识的更准确方法如下:plutil \
-convert json -o - \
"$HOME"'/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist' \
| jq -r '.LSHandlers[] | select( .LSHandlerURLScheme=="https" ) | .LSHandlerRoleAll'
/Applications
下的应用程序路径,你可以执行以下操作:mdfind kMDItemCFBundleIdentifier = "$(
plutil \
-convert json -o - \
"$HOME"'/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist' \
| jq -r '.LSHandlers[] | select( .LSHandlerURLScheme=="https" ) | .LSHandlerRoleAll'
)" \
| grep -E '^/Applications/'