I’ve been increasing my linux mojo the past months and I’m bothered by the fact that every time I open a terminal (ctrl-alt-t) it opens up in a new window. A git window here, quick vim edit there, htop etc. Before I know it I have a lot of terminals I don’t even use anymore. Setting titles to tell the windows apart was a partial solution but not good enough for me.
Recently I discovered tmux which is a terminal emulator to work with multiple terminals in a single window. It’s somewhat advanced for me but I gave it a shot. You can download it using
sudo apt-get install tmux
A primer can be found here: http://www.danielmiessler.com/study/tmux/. It helped me out in getting started. After about a day I got the hang of the basic commands and loved it. Today I realised I could solve the problem of multiple terminals with tmux. So I will explain to you how I did it.
We have tmux up and running. So by now you know you can run tmux attach to attach to any running session. Running tmux attach -d does the same thing. Except, it disconnects every other client (terminal window in our case) that is running that session. So if you are facing a terminal window with a tmux session and you type tmux attach -d in an other terminal window, the former will detach from the tmux session. So, first of all, we make sure that whenever we open up a new terminal we are dropped in a tmux session.
This is easily done by adding the following line on the bottom of your .bashrc file (e.g., by running nano ~/.bashrc):
[[ $TERM != "screen" ]] && exec tmux
Don’t close this file yet, because we’ll change it soon.
If you were to try this out you would see that everytime you open up a new terminal window it will open tmux. Great!
Next, when we open up a new terminal we want to make sure we jump to our previous tmux session and kill the other window. Easy enough.
First of all, change the line we added to our .bashrc previously to the following:
[[ $TERM != "screen" ]] && exec tmux attach -d
As you know by now, this will disconnect all other sessions. Since we start up tmux immediatly when creating a terminal, detaching from tmux closes our terminal. Excellent, we fixed it!
When you would try this, don’t be suprised if you can’t open any terminals anymore. This is normal. When you have no tmux sessions running and you execute tmux attach -d, tmux will tell you you have no sessions and quit. Ergo, you need to tell tmux to create a session if there is no running session. Fair enough.
You should create or modify the file ~/.tmux.conf and add the following line (e.g., by running nano ~/.tmux.conf):
#if run as "tmux attach", create a session if one does not already exist new-session -n $HOST
This piece of setting makes sure the new session is created when you run tmux attach -d when no sessions are present.
That’s about it!