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

Leave a Comment

You must be logged in to post a comment.