I was introduced to Tmux about eight years ago, when I had to keep a server process running on a Digital Ocean droplet even after I closed my ssh connection. This could be done as a detached process, but at the time I was not comfortable running things in the background in a Linux environment. This was the solution I found, I ended up using it for this application for several years.
Tmux is a
Terminal Multiplexer, and it runs as a separate process from your ssh shell. It host one or more persistent sessions that will run basically indefinitely. You can also run Tmux on your local machine, which gives you the ability to switch between sessions as if they were tabs in your browser.
To install Tmux on Linux:
$ sudo apt install tmux
$ brew install tmux
To start simple, let’s just look at how I used to use this, then we can always expand later, if I ever do go deeper into the topic.
To start a new session from a fresh restart:
That’s it. You are now in a Tmux session, and can do things like running a server:
(tmux) $ python server.py *ping* server.py says: still running... *ping* server.py says: still running... *ping* server.py says: still running...
If you close your terminal, the Tmux session will continue running. But more often than not, you want to detach from a session without quitting the terminal. This can be achieved by running the detach command
Ctrl+b d, that is:
hold down the 'Control' key prees 'b' release the 'Control' key press 'd'
You are now back in your original shell.
$ tmux // Note, this was the previous command that started the session in the first place [detached (from session 0)]
In order to reattach your shell to the Tmux session, you simply run:
$ tmux attach *ping* server.py says: still running... *ping* server.py says: still running...
As the text says, the process is still running. This is how I used to manage my server without starting it in detached mode. There are better ways of solving this problem, but this is very close to how I would normally run scripts, and so it allowed me to achieve my goal with minimal effort.
Of course the Tmux rabbit hole goes much deeper. For example:
# Switching between multiple sessions: tmux attach-session -t 0 # Splitting windows horizontally into two panes: Ctrl+b % # Splitting windows vertically into two panes: Ctrl+b " # Iterating through panes: Ctrl+b o
And much, much more.