在Shell脚本中获取OS X应用程序的捆绑包标识符


54

一种选择是使用AppleScript:

$ osascript -e 'id of app "Finder"'
com.apple.finder

您还可以执行以下操作:

$ bundle=$(mdfind -onlyin / kMDItemKind==Application | grep -i "/Finder.app$" | head -1)
$ defaults read "$bundle/Contents/Info" CFBundleIdentifier
com.apple.finder

但这两个都相当慢(在我的空中大约是0.05-0.2s)。有没有更快或更简单的选择?


1
使用defaults read似乎是正确的方法(或者通过Obj-C查询LaunchServices)-为什么您认为0.1s慢?
阿斯姆斯

我喜欢osascript解决方案。但是,您需要每秒运行多少次?
2015年

Answers:


38

如何直接使用PlistBuddy(8)从应用程序的Info.plist文件中读取捆绑包标识符:

/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' /Applications/Safari.app/Contents/Info.plist

19

mdls -name kMDItemCFBundleIdentifier -r SomeApp.app


8

采用 lsappinfo

CC@~ $ lsappinfo info -only bundleid Finder
"CFBundleIdentifier"="com.apple.finder"

要仅获取bundleid值,请添加| cut -d '"' -f4到该命令

CC@~ $ lsappinfo info -only bundleid Finder | cut -d '"' -f4
com.apple.finder

您无需使用该应用程序的路径来处理代码,即使路径更改也是如此。

只要启动应用程序,您就可以获得价值。

尽管它的速度不如@surry的答案,但它足够快。


我不是拒绝投票的人,但这对我来说并不可靠(而其他方法则行)。它适用于某些应用程序,但不是全部。
user137369

@ user137369你能告诉我那是什么应用吗?顺便说一句,该应用必须启动才能使用lsappinfo
user1641838

4
lsappinfo仅适用于当前运行的应用程序。
嗯。

1

kMDItemKind取决于当前本地化。

这个怎么样?

mdls -name kMDItemCFBundleIdentifier \
     -raw "$(mdfind "(kMDItemContentTypeTree=com.apple.application) && (kMDItemDisplayName == 'photoshop*'cdw)" | head -1)"

0

如果启用了显示所有文件扩展名的显示,则kMDItemDisplayName包含用于某些应用程序的.app,但不适用于其他应用程序。这也将逃脱包含姓名'"\

a="Consultant's Canary"; a="${a//\'/\'}.app"; a=${a//"/\\"}; a=${a//\\/\\\\}; mdls -name kMDItemCFBundleIdentifier -raw "$(mdfind 'kMDItemContentType==com.apple.application-bundle&&kMDItemFSName=="'"$a"'"' | head -n1)"

另外一个选项:

a=Finder; mdls -name kMDItemCFBundleIdentifier -raw "$(mdfind kMDItemContentType==com.apple.application-bundle | sed -E $'s|(.*/)(.*)|\\1\t\\2|' | grep -F $'\t'"$a".app -m1 | tr -d '\t')"

单个osascript命令可能也会更快:

osascript -e 'on run args
set output to {}
repeat with a in args
set end of output to id of app a
end
set text item delimiters to linefeed
output as text
end' Finder 'AppleScript Editor'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.