#!/bin/bash help() { self=`basename $0` cat <&2 Reconnect to remote host after connection broken -- 3/22/21 brent@mbari.org All args through user@hostname are passed to ssh Any remaining args are interpreteed as a shell command to be run in a new GNU screen session as user@hostname If no command is specified, try reconnecting with the previous screen session Any -options between user@hostname and the command are passed through to screen Examples: \$ $self esp@koa.tun esp #new interactive esp server session \$ $self esp@koa.tun espclient chris #new esp client session named 'chris' \$ $self esp@koa.tun #reconnect to most recent session \$ $self esp@koa.tun espclient bob #new esp client session named 'bob' \$ session=chris $self esp@koa.tun #reconnect to session 'chris' \$ $self esp@koa.tun -list #list all esp@koa.tun screen sessions If the network disconnects, try to reconnect every 30 seconds, or whenever key pressed at the '...' prompt Environment Variable: session=name #names the session being started or reconnected If session is unset when starting a new one, the name of the new session is the last non-option word in the command used to start it. If session is set to the null string, no attempt is made to guess at the new session name. Bugs: ssh command errors are mistaken for disconnections Use Ctrl-C to exit at the '...' prompt. END exit 2 } ssh="ssh -t" userHost= set -f #no globbing while [ "$1" ]; do ssh="$ssh $1" case "$1" in -*) shift; continue esac userHost="$1" break #assume 1st non-opt is user@host done [ "$userHost" ] || help shift [ "$1" -a -z ${session+x} ] && for arg; do case "$arg" in -*) continue esac session=${arg//\//+} #change slashes into plus signs done if [ "$session" ]; then screen="-S $session $@" resume="-xr $session" else screen="$@" resume="-xRR" fi [ "$1" ] || screen=$resume #echo "$ssh screen $screen ($resume)"; exit #uncomment for debugging while $ssh screen $screen; err=$?; [ $err = 255 ]; do read -t30 -p"`date`: Reconnecting to $userHost in 30 seconds ..." || echo >&2 screen=$resume done exit $err