Automatically reattach to a screen session after logging in via ssh

The following code when added to your .bashrc file will, after logging in via ssh, look for any unattached screen sessions and automatically attach to the first one found. If only attached sessions are found then a list of these will be outputted to std out. Finally, If there are no screen sessions running at all then a new screen session will be created.

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
    screen -U -R
  fi
fi

Optionally adding the following will alter your prompt to let you easily know which window within a screen session you are currently in.

if [ $TERM = "screen" ]; then
  PS1='window ${WINDOW} '$PS1
fi

NOTE: screen is not always installed by default so you may need to grab it before using the above. It should be available via your distros package manager.

Regards, Bawdo

tags: gnu screen, Linux

Mon 27 Nov 2006, 16:49

0 comments

Back