Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to achieve the following behaviour:

When I launch iTerm2, if there is a tmux session running, connect to it. If there is no tmux session running, create one and connect to it.

Any pointers greatly appreciated!

share|improve this question
Note that iTerm2 now has built in tmux support. I don't know how to best make use of it (and thus found this through a search to learn about it), but things should be significantly simpler now. It'd be great to see this updated for this new workflow. – Matt B. Jan 26 '12 at 22:36
Not sure about setting it up to auto connect, but there is information here which could help you modify @Felix's script. – askewchan Jan 9 at 19:46

I use this script, which is execd whenever my shell starts as a login shell. You'll probably want to edit this a bit...

#/usr/bin/env zsh

local tmux=$1
local sname
local ssh

[[ -z "$tmux" ]] && tmux=tmux

# export COLORTERM to fix some programs
case "$TERM" in
    export COLORTERM="$TERM" ;;

# build a fancy session name
[[ ! -z "$SSH_CLIENT" ]] && ssh="/$SSH_CLIENT"
sname=$(print -P "%D{%Y-%m-%d-%H-%M-%S}/%n/%y$ssh")

# make sure session 0 exists  
$tmux has-session -t 0 2>/dev/null || $tmux new-session -d -s 0

# create our own mirroring session
$tmux new-session -d -s "$sname" -t 0

# this doesn't return until the session is closed or detached
$tmux attach-session -t "$sname"

# kill the mirroring session if it's not dead already 
$tmux has-session -t "$sname" 2>/dev/null && $tmux kill-session -t "$sname"

# return to prompt outside of tmux if special file is present 
if [[ -f "$TMUX_LEAVE_SHELL_FILE" ]]; then
  exec zsh -i

Relevant section in my .zshrc

# drop into tmux if this is a login shell and we're not in tmux already
if (which tmux >/dev/null) && [[ -o login ]] &&  [[ -z "$TMUX" ]] && [[ -f ~/etc/script/tmux-login ]]; then
  exec zsh "$HOME/etc/script/tmux-login" $(which tmux)

# handy command to detach tmux but keep the shell running (kind-of)
case $TERM in
    alias detach="touch $TMUX_LEAVE_SHELL_FILE && tmux detach" ;;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.