I need to to get current foreground application's name or PID in OS X? How to get it using terminal?
Asked
Active
Viewed 5,675 times
10
-
it could be done through `wmctrl` – Avinash Raj Jul 01 '14 at 16:44
-
It should be used by standard command. I don't want to install any additional libs/commands etc. – Serge Jul 01 '14 at 16:49
-
Probably something involving AppleScript; you might get a better response at apple.stackexchange.com. – chepner Jul 01 '14 at 17:33
1 Answers
28
You can find this information from the terminal using the 'lsappinfo' command. The man page has a lot of detail about the huge amount of information that this tool can return.
In order to get the frontmost application, you can call lsappinfo with the front argument.
$ lsappinfo front
ASN:0x0-0x10010:
This returns the unique application specifier (ASN) that launch services uses to identify processes. You can feed that back in to lsappinfo to get more details about that process.
$ lsappinfo info `lsappinfo front`
"Terminal" ASN:0x0-0x10010: (in front)
bundleID="com.apple.Terminal"
bundle path="/Applications/Utilities/Terminal.app"
executable path="/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal"
pid = 652 type="Foreground" flavor=3 Version="326" fileType="APPL" creator="????" Arch=x86_64
parentASN="loginwindow" ASN:0x0-0x1001:
launch time = 2014/06/25 15:13:00 ( 8 days, 39 minutes, 25.0882 seconds ago )
checkin time = 2014/06/25 15:13:00 ( 8 days, 39 minutes, 24.6907 seconds ago )
launch to checkin time: 0.397498 seconds
The info flag takes a -only flag to only return certain fields. Using that, you can query for the PID, the app name, the path to the app bundle, etc.
$ lsappinfo info -only pid `lsappinfo front`
"pid"=652
$ lsappinfo info -only name `lsappinfo front`
"LSDisplayName"="Terminal"
$ lsappinfo info -only bundlepath `lsappinfo front`
"LSBundlePath"="/Applications/Utilities/Terminal.app"

Jay Lyerly
- 457
- 4
- 6