Autostarting tmux with multiple windowsPublished: 2014-07-15
Tmux, a lightweight terminal multiplexer, can be configured to open multiple windows upon startup. On my server, I always found myself opening five or more windows. I'll show you how to automate this, through a systemd service file.
User services go in
/etc/systemd/user/. To link a service to a specific user, you need to suffix the service name with @user, e.g. firstname.lastname@example.org.
This is how mine looks:
[Unit] Description=Start tmux in detached session [Service] Type=oneshot User=%I RemainAfterExit=yes ExecStart=/usr/bin/tmux new-session -d -s %u -n 'rtorrent' 'rtorrent' ExecStart=/usr/bin/tmux new-window -t %u:1 -n 'root' ExecStart=/usr/bin/tmux new-window -t %u:2 -n 'lighttpd' 'cd /var/log/lighttpd/; tail -f access.log' ExecStart=/usr/bin/tmux new-window -t %u:3 -n 'music' 'cd /home/tim/music/; bash -i' ExecStop=/usr/bin/tmux kill-session -t %u WorkingDirectory=/home/tim [Install] WantedBy=multi-user.target
I symlinked the service into
/etc/systemd/system/multi-user.target.wants/, so systemd runs it when booting to the default runlevel. The first ExecStart line creates a new session; the next lines open new windows in that session.
A few explanations are in order.
- Type: The oneshot service type allows multiple ExecStart lines. When set to forking, you only get to have one ExecStart line.
- %I: Unescaped instance name [sic]. Refers to the username part of the command used to manipulate the service (enable, start, stop, ...)
- RemainAfterExit: Systemd will still consider the service active after the process has exited.
- -s %u: Sets the session name, here to the user (%u) specified in the service name.
- -n 'root': Sets the window name. After the name, in single quotes, can follow a command, in single quotes as well. Window #2, for example, is called 'lighttpd' and shows Lighttpd's access log.
- :1: This indicates the window. Numbering starts from zero. You can assign window IDs at will.
- WorkingDirectory: the directory the tmux session will open in. This is particularly handy.
I am impressed with systemd's capabilities, although it took quite a bit of tinkering to get it where I wanted it to be. I used to launch tmux from rc.local, using sudo to launch it as a regular user, but that messed up the locale settings. No such thing with systemd.