The One with the Thoughts of Frans

More Fun with Screen and SSH with Byobu: Automatic Reattaching

A while ago I wrote about screen, which makes your SSH experience more satisfying. There are some enhancements you can make to screen with .screenrc, but Byobu does more by default than I ever could be bothered to figure out. It seems to come pre-installed on Ubuntu, while aptitude install byubo suffices for Debian.

I thought it’d be even better if screen automatically attached itself when logging in through SSH, and clearly I wasn’t alone in that thought. I made a slight adjustment to the code I found so that Byobu is utilized when available and otherwise regular screen will load. Screen is often installed by default, unlike Byobu, so that way I won’t have to install or compile Byobu to reap the benefits of my custom .bashrc.

# From http://tlug.dnho.net/node/239
# "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
		type -P byobu &>/dev/null && byobu -U -R || 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

2 Comments

  1. […] I’ve never got around to doing that anywhere – there are a number of examples online (this one for instance) if you want to try […]

    January 15, 2015 @ 20:46Permalink
    Fixed: SSH connection lost during server upgrade – How to reconnect to process? #development #it #fix | SevenNet

  2. […] here for more information about this automatic reattaching […]

    November 11, 2021 @ 13:02Permalink
    SSH'ing to my machine attaches an existing screen session and detaching it ends my SSH session - Boot Panic

RSS feed for comments on this post· TrackBack URI

Leave a Comment

You must be logged in to post a comment.