Working with many sessions

tmux · Practical · 9 min

Once tmux is your workspace, quick switching between projects and servers is what keeps it organised.

One session per project or task keeps windows manageable. From inside tmux:

  • C-b s shows a tree of sessions; pick one to switch the current client to it.
  • C-b ( and C-b ) switch to the previous / next session, C-b L to the last one used.
  • C-b $ renames the current session.
  • C-b :new -s api creates a new session without leaving tmux (you are switched to it).

From the shell, tmux switch-client -t api does the same, and tmux kill-server ends every session at once.

Remote work. Run tmux on the server, not on your laptop, when the point is to survive disconnects: ssh host -t 'tmux new -A -s main' connects and attaches in one go (-t forces a terminal, which tmux needs). If you also run tmux locally, you now have nested tmux: the outer one catches C-b. Press C-b C-b to send the prefix to the inner tmux, or use a different prefix on servers.

Inside tmux the environment variable $TMUX is set. Shell startup files can check it, for example to auto-attach only when not already inside tmux: [ -z "$TMUX" ] && tmux new -A -s main.

Several clients can attach to the same session at once (say, for pair programming); they all see and control the same windows.

Example

tmux new -d -s api -c ~/code/api     # create detached, in a directory
tmux new -d -s web -c ~/code/web
tmux ls                              # api: 1 windows ... / web: 1 windows ...
tmux attach -t api
#   C-b s      choose a session from a tree
#   C-b )      next session
#   C-b $      rename session
ssh prod-1 -t 'tmux new -A -s main'  # attach on a server in one step
[ -z "$TMUX" ] && echo "not inside tmux"

Remember

  • C-b s picks a session, C-b ( and ) cycle, C-b $ renames
  • ssh host -t 'tmux new -A -s main' for remote persistence
  • Nested tmux: C-b C-b sends the prefix to the inner one

Watch out for

  • Running long remote jobs in a local tmux pane: a dropped connection still kills them. Run tmux on the server.

Check yourself

  1. Why is `-t` needed in `ssh host -t 'tmux new -A -s main'`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: github.com/tmux/tmux/wiki/Getting-Started