DEV Community

Kenneth Lum
Kenneth Lum

Posted on

A 5-minute guide to using tmux

What if we ssh to a machine and hope that even when we lose the ssh connection, we can come back to it as if nothing has happened?

For example, if we start up a Rails or Django server and hope to keep it running.

It is really simple with tmux.

Just create some aliases first and add to your .bashrc:

alias tmuxls='tmux ls'      # see all the sessions
alias tmuxn='tmux new -s'   # start a new session
alias tmuxa='tmux a -t'     # attach back to a session
Enter fullscreen mode Exit fullscreen mode

That's it. Next time after you ssh, you can start a session:

tmuxn foo
Enter fullscreen mode Exit fullscreen mode

or

tmuxn server
Enter fullscreen mode Exit fullscreen mode

and now you have a session called "foo" or "server". If your ssh got disconnected, simply ssh back, and do a

tmuxa foo
Enter fullscreen mode Exit fullscreen mode

and you will be able to go back to that session.

Inside, you can press Ctrlc to stop the command (such as the Rails server), and press Ctrld to end the session if you want.

You can have multiple terminals or bash attach to the same session. Simply use

tmuxa foo
Enter fullscreen mode Exit fullscreen mode

in that shell.

And to "detach", simply press Ctrlb, and then d. The session will still be there, and you can attach back to it any time you want.

To end that session, stop anything you are running in that session by Ctrlc, and press Ctrld.

That's it. That's all is needed to start using tmux. The basic idea is:

  1. To create a new session
  2. To attach back to it
  3. To detach from it if you want to (usually we don't have to)
  4. To see all the sessions

We can ssh once to start a tmux session and run the Rails server, and ssh in another terminal to do the usual tasks. Scrolling up and down is easier inside a normal shell.

If you need to turn off your local machine, simply "detach" your session, and exit from the ssh, and now you can shut down your machine. Next time after you turn on your machine, simply ssh back to the remote machine, and tmuxa foo and get back to that session.

If you want, you can make these shorter aliases:

alias tls='tmux ls'      # see all the sessions
alias tn='tmux new -s'   # start a new session
alias ta='tmux a -t'     # attach back to a session
Enter fullscreen mode Exit fullscreen mode

Top comments (0)