How to manage tmux sessions effectively?

Quick Answer

tmux session management commands: tmux new-session -s name (create), tmux attach -t name (attach), tmux ls (list), tmux kill-session -t name (delete), Ctrl+b d (detach), Ctrl+b $ (rename).

tmux new -s dev

Detailed Explanation

Sessions are the core organizational units in tmux. A session can contain multiple windows, and each window can contain multiple panes. Effective session management is key to a productive tmux workflow.

Creating sessions:

# Create a new session named "dev"
$ tmux new-session -s dev

# Short form
$ tmux new -s dev

# Create a new session and run a command
$ tmux new -s logs -d 'tail -f /var/log/system.log'

# Create a new session with specific window name
$ tmux new -s project -n editor

Listing sessions:

# List all sessions
$ tmux list-sessions

# Short form
$ tmux ls

Attaching to sessions:

# Attach to a session named "dev"
$ tmux attach-session -t dev

# Short form
$ tmux a -t dev

# Attach or create if it doesn't exist
$ tmux new-session -A -s dev

Detaching from a session:

To detach from the current session (leaving it running in the background):

# Using key binding
Ctrl+b d

# Using command
Ctrl+b :detach

Renaming sessions:

# Using key binding
Ctrl+b $

# Using command
Ctrl+b :rename-session new_name

Switching between sessions:

# List sessions and select interactively
Ctrl+b s

# Switch to next session
Ctrl+b )

# Switch to previous session
Ctrl+b (

Killing sessions:

# Kill a specific session
$ tmux kill-session -t dev

# Kill all sessions except the current one
$ tmux kill-session -a

# Kill all sessions except "dev"
$ tmux kill-session -a -t dev

Pro Tip

For persistent sessions across system reboots, install the tmux-resurrect and tmux-continuum plugins:

# In your ~/.tmux.conf
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'

# Enable automatic restore
set -g @continuum-restore 'on'