How to switch focus to the app based on its PID from CLI?

I've started using Firefox with multiple profiles, however sometimes I'm lost and I can't find the right window.

For example given I've the process with PID 1234 such as:

$ ps wuax | grep -w Foo
kenorb           1234  /Applications/Firefox.app/Contents/MacOS/firefox -P Foo

how can I switch the current focus to it based on its PID?


Here is an example AppleScript code snippet that will bring the windows of the unix id (PID) for process showing Foo in its command to the front:

set thisUnixID to (do shell script "ps wx | awk '/[F]oo/{print $1}'") as integer

tell application "System Events"
    set frontmost of every process whose unix id is thisUnixID to true
end tell

Note that this example code can be reworked to ask for a profile name and go from there and can be done either as an AppleScript application or a bash script depending on your requirements.

Also note that the square braces around the first character of "Foo" are there so it only returns the PID for the appropriate target, not e.g. the PID of awk looking for "Foo" without the square braces.


Here is the slighty modified version which finds the Firefox window with specific profile name:

#!/usr/bin/env osascript
set PID to (do shell script "pgrep -f -- 'firefox -P Foo'") as integer

tell application "System Events"
  set frontmost of every process whose unix id is PID to true
end tell