Linux Tips guides, explanations and reader checklists on whilenetworking.com

How to Use ‘tmux’ for Persistent Multiplexed Terminal Sessions

In the world of Linux administration and development, losing your work because a network connection dropped or you accidentally logged out can be a…

In the world of Linux administration and development, losing your work because a network connection dropped or you accidentally logged out can be a nightmare. The solution lies in terminal multiplexers, with tmux being the industry standard for managing persistent sessions. Unlike simple screen splitters that only manage layout, tmux allows you to detach from a session, close your terminal window, and return hours later to find your processes running exactly as you left them. This guide provides a comprehensive overview of how to use tmux effectively, covering installation, basic navigation, creating persistent sessions, and best practices for avoiding common pitfalls.

What is tmux and Why Use It?

Terminal multiplexers allow you to run multiple terminal sessions within a single window. While tools like screen have existed for decades, tmux has become the preferred choice due to its robust feature set, including pane splitting, mouse support, and better integration with modern shells. The core benefit of tmux is persistence. When you start a session inside tmux, the environment remains active even after you disconnect your SSH connection or close your terminal emulator.

This capability is essential for several scenarios:
* Long-running processes: You are compiling code, running a database migration, or training a machine learning model and need to walk away for lunch without interrupting the job.
* Unstable connections: You are working on a remote server with an unreliable internet connection; if the link drops, your work stays safe until you reconnect.
* Collaboration: You can share a session with another developer via SSH tunneling or screen sharing tools while maintaining individual panes for different tasks.

Installation and Initial Setup

Before diving into commands, ensure tmux is installed on your system. On Debian-based systems (like Ubuntu), run sudo apt install tmux. For RHEL-based systems (like CentOS or Fedora), use sudo dnf install tmux or sudo yum install tmux. macOS users can install it via Homebrew with brew install tmux.

Once installed, start a new session by typing tmux new-session -s <name>, where <name> is an optional identifier for your session. If you omit the name, tmux will generate one automatically (e.g., session-1). To verify you are inside a session, look at the top left corner of your terminal; it should display [session-name].

Managing Sessions and Panes

The interface is controlled by keyboard shortcuts, which become muscle memory quickly. The most critical command is the prefix key combination: Ctrl + b. Pressing this twice without other keys will detach you from the session immediately. To reattach to a specific session later, use tmux attach -t <session-name>. If you are unsure of the session name, simply press Ctrl + b, then type : and hit Enter; this brings up a command prompt where you can list sessions with list-sessions or detach all with kill-session.

Inside a single session, you can split your screen to multitask. Press Ctrl + b, then press " to split horizontally (top/bottom) or % to split vertically (left/right). You can navigate between panes using Alt + Arrow Keys or click and drag with the mouse if enabled in your configuration. To close a pane, press Ctrl + b, then x. If you confirm the action, that pane closes; if another pane exists, it will resize to fill the space.

Creating Persistent Sessions for Background Jobs

The primary use case for persistence involves running background jobs. A common mistake is starting a long process in the foreground and forgetting to detach. Instead, follow this workflow:
1. Start your session: tmux new-session -s my-build.
2. Run your command (e.g., make build or python train.py).
3. While the process is running, press Ctrl + b, then d to detach. Your terminal will say “detached,” but the process continues.
4. Close your terminal window safely.
5. Later, log back in and run tmux attach -t my-build.

Your process resumes instantly. To ensure a command runs even if you detach immediately, you can use nohup or disown outside of tmux, but wrapping these inside tmux provides additional context management (like viewing logs in the same pane). For example, you can run tmux new-session -s log-monitor -c /var/log/syslog and then split the pane to monitor a specific application log while keeping your main terminal open for editing code.

Advanced Configuration and Customization

The default keybindings are functional, but many users customize them for efficiency. The configuration file is located at ~/.tmux.conf. Open this file in your text editor to add custom commands or change bindings. A common improvement is to enable mouse mode so you can click to select text or resize panes:

set -g mouse on

You can also set up a keybinding to run a command and immediately detach, which is useful for fire-and-forget tasks. Add the following to your config:

bind k run-shell "tmux new-session -d -s backup"

This binds the k key to start a detached session named “backup”. Note that running complex commands directly in tmux.conf can be risky; it is safer to create a script file and source it.

Common Mistakes and Troubleshooting

Users often encounter issues related to signal handling. If you detach from a session (Ctrl + b, then d) while a background job is waiting for user input (like vim or an interactive shell), the process might hang upon reattachment. To prevent this, always run long-running tasks that do not require interaction in detached mode or ensure they are properly daemonized.

Another frequent error is creating too many sessions without naming them. When you detach from unnamed sessions, tmux assigns generic names like session-1, session-2. If you close your terminal and try to reattach later without remembering the exact session name, you may attach to the wrong one or fail entirely. Always use descriptive names (e.g., -s database-migration) when creating sessions.

If you accidentally kill a session while it is active, the process will terminate unless you have used nohup or redirected output to a file within that session. To list all running sessions and their PIDs, type tmux list-sessions -F "#{session_name},#{pid}". This helps in identifying which processes belong to which session before detaching or killing them.

Conclusion

Mastering tmux transforms how you interact with the Linux command line, turning fragile terminal sessions into resilient workflows. By learning to detach and reattach sessions, split panes for efficient multitasking, and configuring your environment for specific needs, you significantly reduce the risk of losing progress due to network interruptions or accidental logouts. Remember that tmux is a tool for managing state; always name your sessions clearly and avoid running interactive commands in detached mode unless necessary. With these practices, you will find yourself spending less time restarting jobs and more time productive work.