Automatic Shell Session Setup

This is the setup I use to make sure that my IRC client is running even after the host reboots.

First, we tell cron to start the session after every reboot (update 2015-03-22: this does not always work, see bottom of this post for potential remedy).

crontab -e
1
@reboot ~/.start-tmux-auto

The actual starting of the session is done with a shell script which calles tmux a few times.

~/.start-tmux-auto
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash

export SHELL=/bin/bash

source ~/.bash_profile

if tmux has-session -t auto > /dev/null 2>&1; then
        :
else
        tmux new-session -d -s auto -n irssi irssi
        tmux new-window  -d -t auto
fi

And we make tmux look and feel a bit more like screen.

~/.tmux.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# set Ctrl-a as the default prefix key combination
# and unbind C-b to free it up
set -g prefix C-a
unbind C-b

# use send-prefix to pass C-a through to application
bind a send-prefix

# reload ~/.tmux.conf using PREFIX r
bind r source-file ~/.tmux.conf \; display "Reloaded ~/.tmux.conf"

# start window numbering at 1 instead of 0 (like numbers on the keyboard)
set -g base-index 1

# screen-like black-on-white statusbar
set -g status-fg black
set -g status-bg white

Now, when I log into the shell host, I attach to my tmux session as follows

Login to shell host and attach to tmux session
1
2
[user@local ~]$ mosh shell
[user@shell ~]$ tmux at

That’s it. For the most part.

Update 2015-03-22

If the @reboot in the crontab fails, it might be because some things on the system need more time to come up properly after booting (e.g. filesystems). In that case, starting the tmux session later might help, as in the following crontab snippet:

crontab -e
1
@reboot echo $HOME/.start-tmux-auto | at now+3min

This works better for me than immediately starting the .start-tmux-auto script, which often failed to start a tmux session.