如何在Mac OS X的bash脚本中获取默认浏览器名称

7
我想在脚本执行前确定Mac OS X机器上的默认浏览器是否为Google Chrome。怎么做?谢谢!
4个回答

9
您可以使用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

1
运行得非常好!谢谢 :) - Brian Clifton

1
无需转换,使用此脚本:

plutil -p ~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist | grep 'https' -b3 |awk 'NR==3 {split($4, arr, "\""); print arr[2]}'

1

获取默认浏览器

以下命令将打印出 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'

1
不确定为什么还没有点赞,但你得到了我的!感谢你详尽而详细的回复。 - SRG

0
当前被接受的答案将首选项文件之一转换为XML,然后再转换回二进制,如果中间出现问题,您的文件可能会损坏。
在使用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/'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接