How can I tell if I'm in a tmux session from a bash script?
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
As for previous answers, testing the ${TERM}
variable could lead to corner cases, tmux
sets environment variables within its own life:
$ env|grep -i tmux TMUX=/tmp/tmux-1000/default,4199,5 TMUX_PANE=%9 TMUX_PLUGIN_MANAGER_PATH=/home/imil/.tmux/plugins/
In order to check if you're inside a tmux
environment, simply check:
$ [ -z "${TMUX}" ] && echo "not in tmux"
After trying different ways, this is what ultimately worked for me, in case it helps anyone out there:
if [[ "$TERM" =~ "screen".* ]]; then
echo "We are in TMUX!"
else
echo "We are not in TMUX :/ Let's get in!"
# Launches tmux in a session called 'base'.
tmux attach -t base || tmux new -s base
fi
In this code snippet, I check to see if we're not in TMUX environment, I launch it. If you put this code snippet in your .bashrc
file, you will automatically run TMUX anytime you open terminal!
P.S.: tested on Ubuntu shell.