Auto-Attach or Start a Tmux Session at Shell Login (with a Smart Check)
Inspired by this helpful post on Coderwall. Full credit goes to the original author!
If you're a terminal-heavy developer like me, you probably live inside tmux
. But there's always that small annoyance: having to manually attach to your session every time you open a new shell. What if your shell could do it for you—automatically?
The Goal
We want to auto-attach to a tmux
session when a new terminal is opened—but only when:
- We're not already inside a tmux session.
- We're not connected via SSH (to avoid weird nested tmux-in-tmux behavior).
The Script
if [[ "$TERM" != "screen" ]] &&
[[ "$SSH_CONNECTION" == "" ]]; then
# Attempt to discover a detached session and attach
# it, else create a new session
WHOAMI=$(whoami)
if tmux has-session -t $WHOAMI 2>/dev/null; then
tmux -2 attach-session -t $WHOAMI
else
tmux -2 new-session -s $WHOAMI
fi
else
# One might want to do other things in this case,
# here I print my motd, but only on servers where
# one exists
# If inside tmux session then print MOTD
MOTD=/etc/motd.tcl
if [ -f $MOTD ]; then
$MOTD
fi
fi
This snippet checks:
- If you're not inside a
tmux
session ($TERM != screen
) - And you're not SSH'd into the machine (
$SSH_CONNECTION == ""
)
If both conditions are true, it will try to attach to a tmux
session named after your username (via whoami
). If it can't find one, it will create a new session for you.
Want to enable it for SSH too?
if [[ "$TERM" != "screen" ]] &&
[[ "$SSH_CONNECTION" == "" ]]; then
To this:
if [[ "$TERM" != "screen" ]]; then
And you’re good to go!
Why This is Handy
- Saves time (no more
tmux attach
every time). - Prevents nested tmux sessions.
- You can still use SSH without getting tmux'd against your will.
Final Thoughts
A small shell tweak like this can make a big difference in your daily terminal workflow. Huge shoutout to Coderwall post by Justin Force for this tip—I just had to share it!
Member discussion