Ubuntu – Key shortcut to invoke last opened terminal

gnome-terminalshortcut-keys

I wonder if there is any way to define a shortcut to maximize / focus on last opened terminal? Ctrl + Shift + T opens a new terminal, and I would like to jump to the last opened instead.

Best Answer

Yes, if you're using Xorg.

Install xdotool:

sudo apt install xdotool

To activate the last used gnome-terminal if one is present, add a custom shortcut with the following command:

bash -c "xdotool windowactivate $(xdotool search --class 'Gnome-terminal' | tail -1)"

To activate the last used gnome-terminal or start a new one if none is present, use the following command:

bash -c "xdotool windowactivate $(xdotool search --class 'Gnome-terminal' | tail -1) || gnome-terminal &"

If you wonder why I used a command substitution with a second xdotool invocation:

From man xdotool:

xdotool supports running multiple commands on a single invocation. Generally, you'll start with a search command (see "WINDOW STACK") and then perform a set of actions on those results.

To query the window stack, you can use special notation "%N" where N is a number or the '@' symbol. If %N is given, the Nth window will be selected from the window stack. Generally you will only want the first window or all windows. Note that the order of windows in the window stack corresponds to the window stacking order, i.e. the bottom-most window will be reported first (see XQueryTree(3)).

In your case, you want the last window, but there is no way to reference it using xdotool's notation, so we let it print all window ids and pipe them to tail in order to retrieve only the last window's id.

The second command above works because if there's no gnome-terminal running, the result of the command substitution is an empty string. The resulting command xdotool windowactivate exits with a non-zero status (because no window id is given), and leads to execution of the right side of the || (logical or) operator.