fluidmind
Star God: Fu Star God: Lu Star God: Shou

The scr Script

Copyright © 2008 by Daniel G. Delaney, Fluid Mind Software

The scr script is a very simple Perl script that makes it easy to manage screen sessions. Screen allows you to give it a name for your session with the -S switch. But it always adds the process ID to that, so that next time you want to attach back to it you have to run "screen -ls" to find out what process ID it added and then type that in to reattach to it. Well, that's just annoying. This script will first check to see if a session already exists with a session name that ends with your username. If it's there you'll be attached to it, if not it will be created. You can also specify a name to use instead of your username.

Two things are great about this. One, you don't have to even know what process ID the screen session was started with. Two, you can put scr in your .profile so that you're automatically dropped into your screen session when you login.

So, say you login to a Linux box with username "joe" and type "scr" at the prompt. A screen session will be started for you with a session name of something like "12345.joe," (but you have no control over what that number will be). Then you detatch from that session and log out. The next time you log back in, again all you have to do is type "scr" and it will re-attach to that "12345.joe" session.

But suppose you have an account on a Linux box that several people use. In that case each user can type their own name after the scr command and each user will have their own sessions. So Joe would type "scr joe", Bob would type "scr bob" and Rufus would type "scr rufus" and you'd end up with three screen sessions with names like "12345.joe", "23456.bob", and "34567.rufus" and none of you have to bother with knowing the process ID that screen used to make your session.

Here's the script:

#!/usr/bin/perl
#
# scr - Checks to see if you already have a screen session going,
#       and starts one if not.
#
# By default, it looks for a screen session with a session name
# corresponding to your username. You can also specify a session
# name on the command line (as in "scr myscreen")
#
# @author   Dan Delaney (http://FluidMind.org)
#

if (@ARGV > 0) {
    $sessionName = @ARGV[0];
} else {
    $sessionName = `whoami`;
    chop $sessionName;
}


# Get the current list of screen sessions
$screens = `screen -ls`;

if ($screens =~ m/(\d{3,5}\.$sessionName)\s+\(([^\)]+)\)/s) {
    if ($2 eq 'Detached') {
        `screen -r $1`;
    } else {
        print "Screen session $1 is already attached to a terminal. Run 'screen -d -r $1' to commandeer it.\n";
    }
} else {
    `screen -S $sessionName`;
}