0
0
Linux CLIscripting~5 mins

tmux for persistent sessions in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you start a task on a remote server and want it to keep running even if you disconnect. tmux helps by creating sessions that stay alive, so you can reconnect later and continue where you left off.
When you want to run a long script on a remote server but might lose connection.
When you need to switch between multiple command-line tasks without closing them.
When you want to share a terminal session with a teammate.
When you want to keep your work organized in separate windows and panes.
When you want to disconnect from a session and reconnect later without stopping your programs.
Commands
This command starts a new tmux session named 'mysession'. You can run your commands inside this session and it will stay alive even if you disconnect.
Terminal
tmux new -s mysession
Expected OutputExpected
myuser@server:~$ tmux new -s mysession [tmux starts with a new window showing your shell prompt]
-s - Names the tmux session for easy reconnecting
This command detaches you from the current tmux session, leaving it running in the background. You can safely close your terminal or disconnect now.
Terminal
tmux detach
Expected OutputExpected
[detaches from tmux session and returns to normal shell prompt] myuser@server:~$
This command reconnects you to the tmux session named 'mysession' so you can continue your work where you left off.
Terminal
tmux attach -t mysession
Expected OutputExpected
myuser@server:~$ tmux attach -t mysession [tmux session 'mysession' window appears with your previous shell state]
-t - Specifies the target session name to attach
Lists all active tmux sessions so you can see which sessions are running and their names.
Terminal
tmux ls
Expected OutputExpected
mysession: 1 windows (created Wed Jun 14 12:00:00 2024) [80x24]
Key Concept

If you remember nothing else from tmux, remember: tmux sessions keep your work running even if you disconnect, and you can reconnect anytime.

Common Mistakes
Closing the terminal without detaching the tmux session
If you don't detach, your session might close and stop running your tasks.
Always detach with 'tmux detach' or press Ctrl+b then d before closing the terminal.
Trying to attach to a session that does not exist
tmux will show an error because it cannot find the session name you typed.
Use 'tmux ls' to check existing sessions and use the correct session name with 'tmux attach -t sessionname'.
Summary
Start a new tmux session with 'tmux new -s sessionname' to keep your work persistent.
Detach safely from a session using 'tmux detach' so it keeps running in the background.
Reconnect anytime with 'tmux attach -t sessionname' to continue your work.
Use 'tmux ls' to list all running sessions and their names.