Skip to content

Instantly share code, notes, and snippets.

@joh6nn
Created October 3, 2017 16:39
Show Gist options
  • Save joh6nn/6237c949c450f2df94ff2922c337638e to your computer and use it in GitHub Desktop.
Save joh6nn/6237c949c450f2df94ff2922c337638e to your computer and use it in GitHub Desktop.
When logging in via ssh, automatically start a tmux session if one is not running. Otherwise, display a list of available tmux sessions, and automatically reconnect to the first available session after a timeout
#! /bin/bash
# When logging in via ssh, automatically start a tmux session if one is not
# running. Otherwise, display a list of available tmux sessions, and
# automatically reconnect to the first available session after a timeout
# Copyright (C) 2017 joh6nn@gmail.com
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#CONFIG:
tmux_opts=""
timeout="${AUTO_TMUX_TIMEOUT:-10}"
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
#check if we're in a ssh connection
if [ "$SSH_CONNECTION" ]; then
#check if tmux is currently running
if [ -z "$TMUX" ]; then
#get list of tmux sessions
tmux_list=$(tmux ls)
#check to make sure list of tmux sessions isn't empty
if [ -n ${tmux_list} ]; then
#display session list (it's a menu)
echo -e "\n$tmux_list"
echo
# prompt, timeout a/f 10s, read only 1 char, default to most recent session
# bash builtin read stores user input in $REPLY by default
read -n 1 -t ${timeout} -p "Pick a # to attach to, or N to start new session: "
if [[ "n" = "$REPLY" ]]; then
#start a new session, so don't need any options
#intentional no-op
tmux_opts=$tmux_opts
elif [ -z "$REPLY" ]; then
#$REPLY is empty, so either we timed out or user hit enter
#default action is to attach to the first available tmux session
tmux_opts="attach"
else
#attach to the entry that the user selected
tmux_opts="attach -t $REPLY"
fi
fi
exec tmux $tmux_opts
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment