Thursday, March 7, 2013

How to force ssh sessions into screen

I can't count how many times I've been working in a terminal session to a remote host and have had the connection drop.  Of course it usually happens when I'm editing a file in Vi or right towards the end of a big download or during a long command causing me have to start over or recover the file.  How do you keep this from happening?  Screen.

Screen is a helpful little script that allows you to connect and disconnect from a machine without losing your place.  It also allows you to do things like open multiple terminal sessions in the same window, share your terminal with other users, and split your window view into multiple terminal sessions.  I use screen regularly, but sometimes forget to start or connect to the session.  Here's how to force your terminal sessions into screen.

We'll start by creating a .bin folder in your user directory (to keep it from getting cluttered)
mkdir ~/.bin

Next we'll add this .bin directory to our path (I know .bash_profile already adds a bin folder, but I want my $HOME directory clean and uncluttered). 
 printf "if [[ -d ~/.bin ]]; then\n\tPATH=$PATH:~/.bin;\nfi" >> ~/.bashrc

Be sure that .bashrc is sourced from your .bash_profile by looking for the following lines in ~/.bash_profile
if [ -f ~/.bashrc ]; then
        . ~/.bashrc

Next we'll create a screen-check script that will actually do the checking and force the session to use screen.  Put the following lines in ~/.bin/screen-check :

# Check if already in a screen and force session into a screen
if [[ $TERMCAP == *screen* ]]; then
        echo "Already in screen"
        screen -dRR myscreen

Then simply add the screen-check script to your .bashrc file and source it 
chmod 755 ~/.bin/screen-check
echo "screen-check" >> ~/.bashrc
source ~/.bashrc

You should now be in a screen session, and every time you open a terminal to the machine it should force you into that session.  Hope that saves someone the headache of having to redo work that got cut off due to a connection issue.

Learn more about screen.

No comments: