Linux Blog

Reattach Screen Script

Filed under: Shell Script Sundays — TheLinuxBlog.com at 2:02 pm on Sunday, April 12, 2009

A friend of mine who happens to be an avid screen user sent me this snippet below:

### Reattach to a screen if one exists ###
if [[ $TERM != 'screen' ]] ; then
if [[ `screen -list | grep -v "No" | awk '$2 { print }' | wc -l` == 0 ]] ; then
screen
else
screen -dr
fi
fi

What this handy snippet does is looks for a screen session, if it finds one it detaches the running screen, and reattaches it(-dr) if it isn’t lucky enough to find one, then it just starts a session up for you. Its rather handy to put in your .bashrc file to auto launch a screen session. The only thing I have modified for my use is replacing -dr for -x to enable me to reattach the screen without detaching the session I may have had open on another terminal. It works pretty well, although when you open a new “screen” CTRL-a + c, the tab doesn’t show up on the other sessions until you change to it, or cycle through them. It isn’t a big deal and could even be a local configuration issue. Anyway, enjoy this snippet and as always let me know if you found it useful.

Man Pages for commands in this post »

screen
grep

2 Comments »

Comment by Derek

May 15, 2009 @ 7:51 pm

try screen -dRR instead

Comment by Chip

May 26, 2010 @ 3:05 pm

Thank you very much. I have been looking for this a very long time. Very helpful. I often run emerge with screen so I can leave the server. Then had trouble re-attaching.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>