bash – How to Tell if in a Tmux Session from a Bash Script

bashprompttmux

I like to keep my bash_profile in a git repository and clone it to whatever machines I have shell access to. Since I'm in tmux most of the time I have a user@host string in the status line, rather than its traditional spot in the shell prompt.

Not all sites I use have tmux installed, though, or I may not always be using it. I'd like to detect when I'm not in a tmux session and adjust my prompt accordingly. So far my half-baked solution in .bash_profile looks something like this:

_display_host_unless_in_tmux_session() {
    # ???
}
export PROMPT_COMMAND='PS1=$(_display_host_unless_in_tmux_session)${REST_OF_PROMPT}'

(Checking every time probably isn't the best approach, so I'm open to suggestions for a better way of doing this. Bash scripting is not my forte.)

Best Answer

Tmux sets the TMUX environment variable in tmux sessions, and sets TERM to screen. This isn't a 100% reliable indicator (for example, you can't easily tell if you're running screen inside tmux or tmux inside screen), but it should be good enough in practice.

if ! { [ "$TERM" = "screen" ] && [ -n "$TMUX" ]; } then
  PS1="@$HOSTNAME $PS1"
fi

If you need to integrate that in a complex prompt set via PROMPT_COMMAND (which is a bash setting, by the way, so shouldn't be exported):

if [ "$TERM" = "screen" ] && [ -n "$TMUX" ]; then
  PS1_HOSTNAME=
else
  PS1_HOSTNAME="@$HOSTNAME"
fi
PROMPT_COMMAND='PS1="$PS1_HOSTNAME…"'

If you ever need to test whether tmux is installed:

if type tmux >/dev/null 2>/dev/null; then
  # you can start tmux if you want
fi

By the way, this should all go into ~/.bashrc, not ~/.bash_profile (see Difference between .bashrc and .bash_profile). ~/.bashrc is run in every bash instance and contains shell customizations such as prompts and aliases. ~/.bash_profile is run when you log in (if your login shell is bash). Oddly, bash doesn't read ~/.bashrc in login shells, so your ~/.bash_profile should contain

case $- in *i*) . ~/.bashrc;; esac
Related Question