Blog is moving

My blog is moving to http://victormendonca.com/blog/. If you are looking for a specific or older post you are in the right place Otherwise check out my new page for more up to date content.

Saturday, March 8, 2008

How to check for a running screen when logging via ssh


For some of you that might have never used screen, it's a program that allows you to create multiple virtual terminals inside one terminal window. You can even break the terminal window into two screens.

I'm not getting into details for the program's usage. You can get more information on these two links:

GNU Screen
How to split screen your command line

In my case, because screen preserves a running program even if your ssh session has lost connection, I use it to download torrents via ctorrent on one of my servers. So when I connect back to my server to check the torrent download status, I have to issue a command like the one bellow to check for running screens, and then connect to it:

$ screen -ls
There is a screen on:
7583.pts-0.pluto (Detached)
1 Socket in /var/run/screen/S-webm.

$ screen -r 7583


A simpler way of doing this would be:

$ screen -DD -R


This command will check for a running screen, and if none is available it will create one. So to make my live a bit easier (and my login a bit fancier), I've added a little script to my ~/.bash_profile (Ubuntu) to prompt me if I want to connect. This is what I get when I login:

Last login: xxxxxxxxxxxxxxxxxxxxxxxxxxxx
There is a screen on:
7583.pts-0.pluto (Detached)
1 Socket in /var/run/screen/S-webm.

A screen was detected, would you like to connect? [y|n]


To achieve that, I appended the following script to my .bash_profile:

## Check for a running Screen
scrtst=`screen -ls | grep 'No Sockets' > /dev/null`
if [ "$?" != "0" ] ; then
screen -ls
echo "A screen was detected, would you like to connect? [y|n] "
read opcao
if [ "$opcao" = "y" ] ; then
screen -DD -R
fi
fi


There are many different ways you can do this. You could even check how many screens are running and list an option to connect to, but I'll leave that up to your imagination.


Vic.



Notes:
- Opcao means option in Portuguese. I like using Portuguese words for variables.
- This idea was adapted from a Linux Journal column - Tech Tip, Use Screen to Avoid Loosing Remote Work - Issue 167

No comments: