One terminal, just one

Apr 2010

Until not-so-long ago, I always had a million terminals open at the same time. I have this neat keyboard-shortcut (Alt-T) which opens a new terminal. That’s nice and all, but the problem is, that I can’t be arsed to alt-tab to my old terminals, leaving a million terminals open, making alt-tabbing between other applications a pain. And I rely quite a bit on Alt-tab, I don’t have any task bar, since I’d rather just alt-tab between stuff than clicking on a task bar (which also takes up precious screen space).

So yes, one day I realised I really had this problem. So I scaled it down, my goal was to: On launch it looks for terminals.

If any terminal is found, this terminal should appear in front of all other windows, instead of launching a new terminal. If, however, no terminals are present, a new one should be launched.

That’s when I realised: “How-the-bob am I going to do this?”- Google to the rescue, and I eventually scaled down each problem in the application, and found a neat little application called wmctrl which (apparently) handles Windows. And by looking a bit at this application, I came up with this script, which handles the problem nicely:

#! /bin/bash
WINTITLE="sakura" # Name of the window (or part of it)
PROGRAMNAME="sakura" # Name of the program, so it can be opened if there's no window currently

# Lists all windows, if there's one containing $WINTITLE it'll return 1, and bring the current instance of the program to the front.
if [ `wmctrl -l | grep -c "$WINTITLE"` != 0 ]
  then
    wmctrl -a "$WINTITLE"
# Else, it'll launch a new instance
else
  $PROGRAMNAME &
fi

# We're good!
exit 0

Just change the variables to reflect your environment, it should be rather obvious what to change. So yeah, you just c/p this script to a whatever.sh file, and put it in your bin and launch your terminal via this script from now on. It’s also in my Kittybin, I might cover some of the other scripts from there in further blog posts. :)

And there we go. Problem solved.