Can I close firefox browser tab or firefox browser from ubuntu terminal?

Option 1. wmctrl

wmctrl can query the window manager for information, and it can request that certain window management actions be taken. (wmctrl manual)

For closing firefox gracefully, wmctrl could do the trick--

wmctrl -c "Firefox" -x "Navigator.Firefox"

you may need to install it first with

sudo apt install wmctrl

Caveat #1

wmctrl -c only closes one window at a time. If you have multiple firefox windows open, you will need to run wmctrl -c multiple times.

Example Solution

while wmctrl -c 'Firefox' -x 'Firefox.Navigator'; do sleep 0.1; done

Caveat #2

Close tabs? confirmation window prompt

If browser.tabs.warnOnClose is set to true, Firefox will prevent the window from closing. This can be changed in about:config, but that is a compromise to your Firefox user experience which may not be worth the risk.

Option 2. xdotool

xdotool lets you programatically (or manually) simulate keyboard input and mouse activity, move and resize windows, etc. (xdotool man page)

ZyMOS was the first to suggest this solution. I'm simply building on their answer by adding additional logic to handle the possible appearance of the close confirmation window.

Example Script

#!/bin/bash
#
# TITLE: close-firefox.sh
#
# DESCRIPTION: Programmatically closes firefox in a way 
#              similar to how a human closes firefox.


# Find the window ID of a Firefox window.
FFWID=$(xdotool search --name "Mozilla Firefox" | head -1)

# use the Firefox window ID to activate that window
xdotool windowactivate --sync $FFWID

# Send the "Quit" hotkey "Ctrl + q" to Firefox.
# https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly
xdotool key --clearmodifiers ctrl+q

# Give the system a moment to process
sleep 0.1

# Find the window ID of the Firefox close confirmation window
CWID=$(xdotool search --name "close tabs")

# End the script if xdotool didn't detect a confirmation window
if [ $? -ne 0 ]; then
  exit 0
fi

# Activate the Confirmation window
xdotool windowactivate --sync $CWID

# Send an "Return" key press to the confirmation window.
# This does the default action of pressing the "Close tabs" button.
xdotool key --clearmodifiers Return

If you wish to "entirely" close Firefox "gracefully", try using xdotool. By gracefully, i mean closing the program, not killing it. By entirely, i mean "quiting" Firefox, closing all windows, all at once. wmctrl will gracefully close a single Firefox window, but will not close all windows.

Create the following script:

#!/bin/bash

WID=`xdotool search "Mozilla Firefox" | head -1`
xdotool windowactivate --sync $WID
xdotool key --clearmodifiers ctrl+q

That should do it.


You cannot close a tab, but you can close the browser using one of these:

pkill firefox
killall firefox