-.- --. .-. --..

Using Tmux for everything

I use Tmux for all terminal work/play sessions. Generally, I just run tmux for every time I want to hack on something unrelated to the sessions I already have. That command will create a new unnamed tmux session which, while useful, that gets quickly unwieldy if you keep doing that often. Wouldn’t it be wonderful if there was a way to start a scratch session whenever I open a new terminal window? Turns out, it’s not that complicated.

After fiddling with a simple shell script, I now have a functional setting where a tmux session named scratch gets connected to whenever a new terminal tab/window is created. To do this, start by create a file called ~/.zprofile — if it already exits, append the code to that file — and drop the following code in it. The reason to add this to that specific file is that the profile config file gets run every time a shell login happens. We would want to start a tmux session right after logging in to the shell.

Note: I use zsh for my shell and this script is tested for that.

tmux has -t scratch &> /dev/null

if [ $? != 0 ]; then
  tmux -2 new-session -s scratch -D -d
fi

if [ -z "$TMUX" ]; then
  tmux attach -t scratch -d
fi

First, we check if there’s a session named scratch, we simply attach to it while detaching all the existing client connections running the same session. This way, we always will have just one window running the scratch session. -d is passed in for this purpose. The tmux has or tmux has-session in it’s long form is used to check if there’s a session already present. This command exits with an exit code of 0 if there is a session or with a code of 1 if there is no such session.

If there’s no session named scratch, we create a session and immediately detach from it by passing the option -d.

We then check if a Tmux session is already running. The [ -z "$TMUX" ] condition will check if the string $TMUX is blank. -z option checks returns true if the string is blank. So, we attach to a session only if it’s not inside a tmux session already. The only thing adding that check did was disable a warning that gets shown when tmux sessions gets nested. This doesn’t happen usually, by the way; this command run only once at login and is unique to each session. But I had to add that check to stop the complaints.

Although this code is pretty simple, since Tmux supports a good level of programmability, more configurations can be achieved. For example, I can add a command that opens two windows, one with pry and another with just the command prompt. Here’s a link I found helpful for creating such sessions.

← Ruby, Trace, Leave, Oh my! Robust File validations in Ruby using magic numbers →