tmux is a terminal multiplexer for Unix-like operating systems.

I do like tmux. And here I'm going to share some of my useful scripts to initialize my tmux environment for different projects.

The Bootstrap Code

Let's see a piece of bootstrap code in .bashrc:

# tmux
# tmux's default config file is ~/.tmux.conf
# Load scripts in ~/.tmux on creating a new pane
# Load order: __before__.sh, ${session_name}.sh, __after__.sh
__env_tmux_load_startup_scripts_by_session_name() {
  if [[ -n ${TMUX} ]]; then
    local session_name="$(tmux display-message -p '#{session_name}')"
    local env_before_script="${HOME}/.tmux/__before__.sh"
    [[ -f "${env_before_script}" ]] && { . "${env_before_script}" "${session_name}"; }
    local env_main_script="${HOME}/.tmux/${session_name}.sh"
    [[ -f "${env_main_script}" ]] && { . "${env_main_script}"; }
    local env_after_script="${HOME}/.tmux/__after__.sh"
    [[ -f "${env_after_script}" ]] && { . "${env_after_script}" "${session_name}"; }
  fi
}

__env_tmux_load_startup_scripts_by_session_name

Once you typed tmux command in your terminal, the bootstrap process will be triggered. And a list of scripts will be loaded by order:

  • ~/.tmux/__before__.sh
  • ~/.tmux/${session_name}.sh
  • ~/.tmux/__after__.sh

${session_name} is the tmux session name, for example, if you typed tmux new -s apple, ${session_name} will be "apple". So, if you had a script named apple.sh under ~/.tmux/ folder, it will also be loaded.

What Can be Done Next

Since above three scripts will be loaded, you can add useful initialization steps to these scripts. For example:

Change directory to project home.

Correct username and email settings for git of your projects.

Like for all my projects with path pattern */github.com/apple/*, my username should be Mingjie. But for all my projects with path pattern */*.googlesource.com/*, my username should be Ggicci.

Load virtual environment for python projects.

Detect virtual environment settings for python projects and load the shell automatically.

Add project specfied steps in ${session_name}.sh file.

__before__.sh and __after__.sh are good places to add common initial scripts for all of your projects. But ${session_name}.sh is designed for a project specified by name.

Here are some of my snippets: https://codelet.io/ggicci/QdoQt5AUBUkx/useful-shell-scripts-for-tmux-environment-initialization