Bash interactive shell hangs when Tmux is suspended if it was automatically started by Bash startup file

bashjob-controltmux

When I manually start Tmux by issuing tmux from my Bash interactive shell I can later suspend Tmux with CTRL-BZ without problems. Pressing this key combination brings me back to the parent process, i.e. the Bash interactive shell from which I started Tmux.

But I've got the following code snippet at the very end of my configuration file for Bash interactive shells (~/.bashrc) defined:

# Test if neither _Tmux_ nor _Screen_ is running.
if ! [[ -n "$TMUX" || "$TERM" =~ screen ]]; then
  # Test if _Tmux_ is on the `$PATH`.
  if type -p tmux &> /dev/null; then
    # Try to attach to latest unattached session or start a new one.
    { tmux attach-session || tmux new-session; } &> /dev/null
  fi
fi

This code snippet automatically starts Tmux whenever I start a Bash interactive shell given that there no terminal multiplexer program running yet.

But pressing CTRL-BZ this time around suspends Tmux leaving me in an unresponsive parent process, i.e. the Bash interactive shell that automatically started Tmux from its startup file (~/.bashrc).

Apart from detaching Tmux from and reattaching it to a session, is there a way to make Tmux suspend in such a way that I can continue to work in its parent Bash interactive shell and come back later foregrounding it with fg?

Please note that for various reasons I intend to let Bash fork Tmux and and not replace itself by it (exec).

Best Answer

You should turn job control on with set -m in your .bashrc before starting tmux.

Bash runs startup files like .bashrc with job control disabled. From shell.c:

#if defined (JOB_CONTROL)
  /* Startup files should be run without job control enabled. */
  old_job_control = interactive_shell ? set_job_control (0) : 0;
#endif

Please notice that C-b C-z does not set tmux in the background by itself; absent job control in the upper shell, the SIGTSTP signal tmux sends itself will just cause it to stop; the tmux process will still be in the foreground process group of the terminal (despite the deceptive switching from the alternate screen with the the exit_ca_mode/rmcup/te escape on some terminal emulators like xterm)

Related Question