Skip to content

Instantly share code, notes, and snippets.

@cameron
Created June 20, 2017 00:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameron/b4d7fae4bc7fdf99cb4eb473e8cc9746 to your computer and use it in GitHub Desktop.
Save cameron/b4d7fae4bc7fdf99cb4eb473e8cc9746 to your computer and use it in GitHub Desktop.
#! /bin/zsh
tmux \
new-session -d -s $sessionName -n emacs 'emacs .' \;\
new-window -n 'app' "bin/run" \;\
new-window -n 'build' "bin/build" \;\
new-window -n 'tests' "bin/test" \;\
new-window -n git \;\
selectw -t emacs
function chpwd_tmux () {
# create and attach to tmux session when entering project directories
if [[ -f .tmux && -z "$TMUX_PROJECT" ]]; then
sessionName=`pwd | sed 's/\/Users\/cameron\/src\///' | tr -d '/-'`
tmux has-session -t $sessionName
if [ $? -ne 0 ]; then
export TMUX_PROJECT=$sessionName
# TODO handle errors in this script better
. .tmux
fi
. tmux-attach-to-project-session # see below
unset TMUX_PROJECT
fi
}
chpwd_functions=(${chpwd_functions[@]} "chpwd_tmux")

cd into workspaces with tmux

Ever since my arranged marriage to emacs at my first full-time programming job, I've felt wedded to terminals. Even when I'm not working on a remote server, I like using tmux to keep multiple workspaces alive without clutter my desktop with so many application windows.

Each of my projects tends to have at 3-7+ separate processes. At least: an editor, a shell for git and file management, and a server/application process. Usually there are also logs, tests, perhaps a ngrok tunnel, and especially with containized systems, some other automation scripts. Since arranging windows and invoking the same build commands for the 10,000th time sucks, I wrote a little bit of bash that, when I cd into a project directory (one that has a .tmux script), will check to see if a tmux session by the directory's name exists, attach to it if so, or run the .tmux script to create one if not. (It also supports multiple monitors.)

Below, you'll find the addition to .zshrc that handles the initiates process on directory-change, a tmux helper script, and a .tmux.example script that creates a new workspace.

#! /bin/bash
# set the terminal title
echo -ne "\e]1;$sessionName\a"
# support multiple monitors
sessions=`tmux list-sessions | grep $sessionName | grep -v attached`
if [ $? -eq 1 ]; then
secondarySessionName=$sessionName-`date +%s`
tmux \
new-session -t $sessionName -s $secondarySessionName \;\
attach -d -t $secondarySessionName \;\
select-window -t 2
return
fi
sessionName=`echo $sessions | head -1 | grep -o "^[^:]*" | head -1`
tmux attach -d -t $sessionName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment