How to safely close all windows of a gui application with a shortcut key
The safest way to close an application's window gracefully, and make sure you will not lose data, is using wmctrl (not installed by default):
wmctrl -ic <window_id>
To use it in a script to close all windows of an application:
install both xdotool
and wmctrl
sudo apt-get install wmctrl xdotool
Copy the script below into an empty file, save it as stop_active.py
#!/usr/bin/env python3
import subprocess
def get(cmd):
return subprocess.check_output(cmd).decode("utf-8").strip()
pid = get(["xdotool", "getactivewindow", "getwindowpid"])
for w in get(["wmctrl", "-lp"]).splitlines():
if pid in w and not "Desktop" in w:
subprocess.call(["wmctrl", "-ic", w.split()[0]])
Add the following command to a shortcut key:
python3 /path/to/stop_active.py
Choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:
python3 /path/to/stop_active.py
N.B. don't use ~
or $HOME
in a shortcut key, but use absolute paths instead.
Now the shortcut can be used to gracefully close all windows of the frontmost window.
Explanation
I tried the various kill
options (kill -2
, kill -HUP
, kill -s TERM <pid>
etc), which are mentioned in several posts to close an application gracefully. Tested on a gedit
window with unsaved changes, all of them closed the window happily however, without any interaction.
wmctrl
does ask what to do however, similar to Ctrl+Q.
The script then first finds out the pid
of the frontmost window, with the command:
xdotool getactivewindow getwindowpid
subsequently, the list of currently opened windows is called with the command:
wmctrl -lp
From this list, the corresponding windows are picked and closed with the command:
wmctrl -ic <window_id>
Note
If you are closing all nautilus
windows, in the line
if pid in w and not "Desktop" in w:
"Desktop"
is referring to your Desktop window, which normally should always stay. If you are not using an English version of Ubuntu, replace "Desktop"
by the localized name of the Desktop in your language.