Last Updated: February 25, 2016
·
2.612K
· cmdel

Automagically connect to a Screen session when SSH'ing in a remote server

If you need to SSH to a remote server, and have the unfortunate luck of connecting via a BTOpezone WiFi --which automatically disconnects me avery 2 hours -- you need to have a way of maintaining the state of your terminal and scripts, when the SSH pipe breaks.
Screen and Tmux are both very good at this. Since Screen is more ubiquitous and can be found pre-installed in most recent *nix flavours, I wanted a way to attach to a screen session once I logged in via SSH.

Add the following to your

.bashrc

file and the next time you SSH back in you'll be attached to an existing session. N.B. that this only works for the first attached session found. It probably won't work for multiple session of Screen very well.

if [ $SSH_TTY ] && [ ! $WINDOW ]; then
    SCREENLIST=`screen -ls | grep 'Attached'`
    if [ $? -eq "0" ]; then
        echo -e "Screen is already running and attached:\n ${SCREENLIST}"
    else
        type -P byobu &>/dev/null && byobu -U -R || screen -U -R
    fi
fi