补充@Bavarious' helpful answer:
以下是通用bash 函数,它们通过返回应用程序的路径或其捆绑包ID(如果已安装)来扩展测试是否安装了应用程序。如果您将它们放在您的 bash 配置文件中,它们也可能会在交互式使用中派上用场。
这两个函数仍然可以作为一个应用程序是否安装的测试;例如:
if ! whichapp 'someApp' &>/dev/null; then ... # not installed
这两个函数都不区分大小写,并且在指定 name 时,.app 后缀是可选的。
但是请注意,本地化名称是不被识别的。
whichapp
通过任一捆绑ID 或名称定位应用程序的功能。
如果找到,则返回应用程序的路径;否则报错。
例子:
-
whichapp finder # -> '/System/Library/CoreServices/Finder.app/'
-
whichapp com.apple.finder # -> '/System/Library/CoreServices/Finder.app/'
bundleid
给定应用程序的名称,返回其捆绑包 ID。
例子:
bundleid finder # -> 'com.apple.finder'
实现说明:在 AppleScript 代码中,很容易绕过 Finder 上下文并简单地使用例如application [id] <appNameOrBundleId> 和 path to application [id] <appNameOrBundleId> 在全局上下文中,但问题是总是启动目标应用程序,这是不受欢迎的。
来源:哪个应用程序
whichapp() {
local appNameOrBundleId=$1 isAppName=0 bundleId
# Determine whether an app *name* or *bundle ID* was specified.
[[ $appNameOrBundleId =~ \.[aA][pP][pP]$ || $appNameOrBundleId =~ ^[^.]+$ ]] && isAppName=1
if (( isAppName )); then # an application NAME was specified
# Translate to a bundle ID first.
bundleId=$(osascript -e "id of application \"$appNameOrBundleId\"" 2>/dev/null) ||
{ echo "$FUNCNAME: ERROR: Application with specified name not found: $appNameOrBundleId" 1>&2; return 1; }
else # a BUNDLE ID was specified
bundleId=$appNameOrBundleId
fi
# Let AppleScript determine the full bundle path.
fullPath=$(osascript -e "tell application \"Finder\" to POSIX path of (get application file id \"$bundleId\" as alias)" 2>/dev/null ||
{ echo "$FUNCNAME: ERROR: Application with specified bundle ID not found: $bundleId" 1>&2; return 1; })
printf '%s\n' "$fullPath"
# Warn about /Volumes/... paths, because applications launched from mounted
# devices aren't persistently installed.
if [[ $fullPath == /Volumes/* ]]; then
echo "NOTE: Application is not persistently installed, due to being located on a mounted volume." >&2
fi
}
注意:该函数还会在给定会话中找到从已安装的卷启动的应用程序谢谢Wonder Dog。,但既然这样应用程序未永久安装(未向 macOS 启动服务永久注册),在该事件中会发出 警告。
如果需要,您可以轻松地修改函数以改为报告错误。
来源:bundleid
bundleid() {
osascript -e "id of application \"$1\"" 2>/dev/null ||
{ echo "$FUNCNAME: ERROR: Application with specified name not found: $1" 1>&2; return 1; }
}