How do I close a new Firefox window from the Terminal?

I have multiple instances of Firefox running in Ubuntu 14.04. How can I close the most recently opened window/instance from the Terminal?

I tried using the cfct alias defined in an answer to a related question, but it didn’t work.


To make a command that finds the id of the last window, created by Firefox (and to close it), you will need wmctrl to be installed:

sudo apt-get install wmctrl

The command

Then use the command:

wmctrl -ic "$(wmctrl -l | grep 'Mozilla Firefox' | tail -1 | awk '{ print $1 }')"


Explanation:

wmctrl -l

lists all windows, but an important property of the command is that it lists the windows in the order they were created.

Therefore:

wmctrl -l | grep 'Mozilla Firefox' | tail -1 | awk '{ print $1 }'

will:

  • list all windows:

    wmctrl -l
    
  • find the ones (the lines) with 'Mozilla Firefox' in their name:

    grep 'Mozilla Firefox'
    
  • find the last one (which is also the last created one):

    tail -1
    
  • extract the first string in the line (which is the window -id):

    awk '{ print $1 }'
    

The command:

wmctrl -ic

will then kill the most recent Firefox window by its id (gracefuly).

Or even more reliable:

While the command above works well in practically all cases, there is a small chance of name clashes, if e.g. another window exists with "Mozilla Firefox" in its name, but not a window from Firefox (unlikely, but still).

What should work "waterproof" is therefore to identify the windows in the window list (using wmctrl -lp) by the pid of firefox, instead of the string in the window name:

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

As you can seen, in this command,

wmctrl -l | grep 'Mozilla Firefox'

producing the lines containing 'Mozilla Firefox', is replaced by:

wmctrl -lp | grep "$(pgrep firefox)"

producing the lines containing the pid of firefox (as the output of pgrep firefox)


To close a window (also with many opened tabs) use that command:

wmctrl -a firefox; xdotool key Ctrl+Shift+w

Notice, that wmctrl and xdotool must be installed:

$ sudo apt-get install wmctrl xdotool

See also that answer: Close current tab firefox using terminal.

My answer is a bit modified, because Ctrl+Shift+w closes a firefox window.


For all shortcuts, see Firefox Keyboard shortcuts.