Skip to content

Instantly share code, notes, and snippets.

@shitchell
Last active February 24, 2021 09:01
Show Gist options
  • Save shitchell/aeffd7dd3e3249f65ce4a02326ff31c1 to your computer and use it in GitHub Desktop.
Save shitchell/aeffd7dd3e3249f65ce4a02326ff31c1 to your computer and use it in GitHub Desktop.
A script for quickly opening and attaching to tmux sessions
#!/bin/bash
# A script for quickly opening and attaching to tmux sessions
#
# It takes two optional arguments: a session name and directory.
# If no session name is provided, "main" is used. If no
# directory is provided, the current directory is used. Then
# it simply switches to that session. If that session doesn't
# exist, it creates it first and sets the default session. You'd
# think this would be trivial, but tmux requires many different
# options to create/attach a session based on the context.
# This just works.
usage() {
echo usage: $(basename "$0") [session] [default-directory]
echo
echo "If no session is provided, 'main' is used. If a default-directory is"
echo "provided, then that directory will be used for all new windows inside"
echo "the session."
echo
echo "Of note, this utility detects whether or not it is being run inside"
echo "an existing tmux connection and can safely create or switch sessions"
echo "without any nesting issues."
echo
echo " -l list sessions"
echo " -h display this help message"
}
## Command line options
while getopts "hl" arg; do
case $arg in
h) usage && exit;;
l) tmux list-sessions && exit;;
esac
done
## Get requested session information
SESSION_NAME="$1"
ATTACH_DIR="$2"
DEFAULT_SESSION="main"
# Ensure the session name is set
if [[ -z "$SESSION_NAME" ]]; then
if [[ -n "$DEFAULT_SESSION" ]]; then
SESSION_NAME="$DEFAULT_SESSION"
fi
fi
## Connect to the session
# Create the session if it doesn't exist
if [[ -n "$ATTACH_DIR" && -d "$ATTACH_DIR" ]]; then
TMUX= tmux new-session -d -s "$SESSION_NAME" -c "$ATTACH_DIR" 2>/dev/null
else
TMUX= tmux new-session -d -s "$SESSION_NAME" 2>/dev/null
fi
# Connect to the session
if [[ -n "$TMUX" ]]; then
# If we're already inside tmux, use switch-client
if [[ -n "$ATTACH_DIR" && -d "$ATTACH_DIR" ]]; then
# TODO: Figure out how to change the directory when switching
# from inside tmux
TMUX="" tmux switch-client -t "$SESSION_NAME" # \; attach -c "$ATTACH_DIR"
else
TMUX="" tmux switch-client -t "$SESSION_NAME"
fi
else
# If we're not inside tmux, use attach-session
if [[ -n "$ATTACH_DIR" && -d "$ATTACH_DIR" ]]; then
TMUX="" tmux attach-session -t "$SESSION_NAME" -c "$ATTACH_DIR"
else
TMUX="" tmux attach-session -t "$SESSION_NAME"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment