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."

About the Author

2 thoughts on “Bash // Create or Attach to Screen Session on Login

  1. A pastor who uses Linux? That’s awesome!

    Are you using Screen for scrollback history and multitasking in one terminal, or is there another benefit I’m not seeing in the man page? I’ve been using multiple SSH connections to my home server, but now I’m thinking Screen is a better solution. Especially when my kids get on my home PC and close my terminal sessions.

    1. The biggest benefit that screen provides is persistence. I can launch a process in a screen session, and if my SSH connection is dropped, the process continues, and I can reconnect at any other time to continue right where I left off. Secondly, in the servers I maintain, I have a screen session constantly running with about 7 “windows” active. I have a couple windows for my local user and a couple windows viewing log files with the tail -f command. It makes my SSH sessions as convenient as the local virtual terminals would be if I were physically at the computer, and it all is restored to me as soon as I connect.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may also like these