Join my Laravel for REST API's course on Udemy 👀

Tmux sessions should be nested with care, unset $TMUX to force

October 15, 2020  ‐ 2 min read

If you try to start a new tmux session from within a tmux session you get the error message sessions should be nested with care, unset $TMUX to force. So what does this mean?

It basically means that tmux doesn't like it if you nest a tmux session in an already active tmux session. Doesn't mean it is impossible to do so. You can nest a tmux session by unsetting $TMUX, helpful error message right. You do this as follows:

$ TMUX='' tmux

This gets you a new tmux session inside your currently active tmux window.

More likely the way to go is to detach from your current session first with tmux detach.

Create and attach to tmux session in shell script

If you're writing a shell script that switches or attaches to a tmux session depending on whether you're in tmux or not you can do that as follows.

  1. First you check if a tmux session exists with a given name.
  2. Create the session if it doesn't exists.
  3. Attach if outside of tmux, switch if you're in tmux.
#!/bin/bash

session_name="sesh"

# 1. First you check if a tmux session exists with a given name.
tmux has-session -t=$session_name 2> /dev/null

# 2. Create the session if it doesn't exists.
if [[ $? -ne 0 ]]; then
  TMUX='' tmux new-session -d -s "$session_name"
fi

# 3. Attach if outside of tmux, switch if you're in tmux.
if [[ -z "$TMUX" ]]; then
  tmux attach -t "$session_name"
else
  tmux switch-client -t "$session_name"
fi

A logical improvement to make based on this script is to get the session name from an argument to your script. So instead of hardcoding the tmux session name to "sesh" you would use the value in $1 for example.