Thanks to Mark for his awesome answer! Expanding on that a little:
# Look up the parent of the given PID.
# From http://stackoverflow.com/questions/3586888/how-do-i-find-the-top-level-parent-pid-of-a-given-process-using-bash
function get-top-parent-pid () {
PID=${1:-$$}
PARENT=$(ps -p $PID -o ppid=)
# /sbin/init always has a PID of 1, so if you reach that, the current PID is
# the top-level parent. Otherwise, keep looking.
if [[ ${PARENT} -eq 1 ]] ; then
echo ${PID}
else
get-top-parent-pid ${PARENT}
fi
}
function bring-window-to-top () {
osascript<<EOF
tell application "System Events"
set processList to every process whose unix id is ${1}
repeat with proc in processList
set the frontmost of proc to true
end repeat
end tell
EOF
}
You can then run:
bring-window-to-top $(get-top-parent-pid)
Quick test using:
sleep 5; bring-window-to-top $(get-top-parent-pid)
And swap to something else. After 5 seconds the terminal running your script will be sent to the top.
https://stackoverflow.com/questions/3586888/how-do-i-find-the-top-level-parent-pid-of-a-given-process-using-bash