Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.)

share|improve this question

1 Answer 1

up vote 23 down vote accepted

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
share|improve this answer
    
There is an alternative variable TMUX_PANE as well. I only noticed because your recipe didn't work. Later I found out that I had unduly used (and subsequently unset) a variable in a shell script I am sourcing through my .profile. –  0xC0000022L Jun 2 at 23:23

Your Answer

 
discard

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.