Bash // Create or Attach to Screen Session on Login

I use GNU Screen for everything I do in Linux… perhaps you do too, but perhaps you are annoyed that every time you log in to a terminal session on your Linux machine, you have to go through the one extra step of reconnecting to your screen session or checking to see if one is already running and then maybe creating a new session.

Here’s a way to make sure whenever you SSH into your Linux server, you always get right back where you were in your previous screen session just like you left it. The added bonus of this is that whenever you detach from your screen session, you are also automatically logged out of the server.

Simply add these lines to the bottom of your .bash_profile (watch out for word wrapping).

# start screen session if not already started
# or connect to screen session if not already in it
echo ''
echo '----------- WE LIKE SCREEN ------------------------------'
if [ ${TERM:0:6} != "screen" ]
    echo "Attempting to connect/create screen session."

    # We don't want to forcibly disconnect other sessions if they are
    # Attached, so we check for Detached sessions first
    HAVE_DETACHED=$(screen -list | grep Detached)
    HAVE_ATTACHED=$(screen -list | grep Attached)

    if [ -n "$HAVE_DETACHED" ]
        echo "Attaching to existing screen session"
        exec screen -r

    elif [ -n "$HAVE_ATTACHED" ]
        echo "Existing screen sessions are all attached"
        echo "use 'screen -rd' to detach and attach here."
        echo "There are no running screen sessions."
        echo "Creating new screen session."
        exec screen
        echo "Already in a screen session. Cool."