Open already running program via terminal

How do I switch to already running program using terminal?

For examaple:

firefox opens new firefox window.

Is there a command that will focus the already opened firefox window?


As a one- liner

Assuming you have wmctrl installed (run sudo apt-get install wmctrl if not):

The command:

wmctrl -ia "$(wmctrl -lp | grep "$(pgrep gedit)" | tail -1 | awk '{ print $1 }')"

Would raise the last opened gedit window. Replace it by any other application.

Explanation

pgrep gedit

gets the pid of gedit

wmctrl -lp

lists all windows and the pid they belong to

awk '{ print $1 }'

splits off the window- id (the first string in the line)

$(wmctrl -lp | grep "$(pgrep gedit)" | tail -1 | awk '{ print $1 }')

therefore finds the window-id of the last created window of gedit (the output of wmctrl -lp lists the windows in a chronological order of creation, if the application has multiple windows, tail -1 returns the last one).

wmctrl -ia

subsequently raises the window by its window-id

In a small script

...to be run with the application as argument:

#!/bin/bash

wmctrl -ia "$(wmctrl -lp | grep "$(pgrep "$1")" | tail -1 | awk '{ print $1 }')"
  • Save it into an empty file as switchto.sh
  • Make it executable
  • Run it as (e.g.)

    /path/to/switchto.sh firefox
    

Alternatives?

Theoretically the command:

xdotool search --class gedit windowactivate

should do (kind of) the same; it should raise the first found window of gedit in this case.
It seems less robust however. On my system (Unity) it did nothing at all.


If you have runned firefox using firefox & you can use jobs to see its number. To bring it to foreground write %n firefox which n stands for its number. Example:

sabrina@ubuntu:~$ jobs
[1]+ Stopped      firefox
sabrina@ubuntu:~$ fg %1

Also you can "kill" the program:

sabrina@ubuntu:~$ kill %1