New tmux sessions do not source bashrc file

As far as I know, by default tmux runs a login shell. When bash is invoked as an interactive login shell, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile. So you have to put source ~/.bashrc in one of those files.

Another way to solve this issue is to put in your file .tmux.conf the line:

set-option -g default-shell "/bin/bash"

This is related to the Bash init files. By default, ~/.bashrc is used in an interactive, non-login shell. It won't be sourced in a login shell. Tmux uses a login shell by default. Hence, shells started by tmux skip ~/.bashrc.

default-command shell-command

The default is an empty string, which instructs tmux to create a login shell using the value of the default-shell option.

Init files for Bash,

  1. login mode:
    1. /etc/profile
    2. ~/.bash_profile, ~/.bash_login, ~/.profile (only first one that exists)
  2. interactive non-login:
    1. /etc/bash.bashrc (some Linux; not on Mac OS X)
    2. ~/.bashrc
  3. non-interactive:
    1. source file in $BASH_ENV

Solution

The weird interactive, non-login loading requirement confuses people in other situations as well. The best solution is to change the loading requirement of ~/.bashrc as interactive only, which is exactly what some distros, like Ubuntu, are doing.

# write content below into ~/.profile, or ~/.bash_profile

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
    fi
fi

This should be the solution you desire. And I recommend every Bash user setup this in the profile.


Update: the above settings is copied from Ubuntu. It seems they choose to load .bashrc in a login shell no matter it's within an interactive shell or not.

If you wanna detect an interactive shell, use $PS1.

if [ -n "$BASH_VERSION" -a -n "$PS1" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
    fi
fi

References

  • Unix Shell Initialization
  • Shell startup scripts
  • man tmux

Adding the following to .tmux.conf:

set-option -g default-shell "/bin/bash"

DOES NOT yield the desired result.

Only when adding source "$HOME/.bashrc" to ~/.bash_profile the intended result is achieved.

This will work on an active tmux session when opening a new window or pane, and also when detaching and opening a new tmux session.

Tested on:

VERSION="16.04.2 LTS (Xenial Xerus)"
tmux 2.1

Tags:

Bash

Tmux