Power Sessions with Screen

January 1st, 2003 by Adam Lazur in

Adam explains the many benefits and uses of screen.

Screen is a terminal multiplexer that allows you to manage many processes through one physical terminal. Each process gets its own virtual window, and you can bounce between virtual windows interacting with each process. The processes managed by screen continue to run when their window is not active.

Thus far, the screen features described aren't all that exciting or new. In fact, there already are X11 terminal applications that provide this functionality (konsole and multi-gnome-terminal). What differentiates screen from the others are some of the core features screen provides.

Screen offers the ability to detach from a session and then attach to it at a later time. When detached from a session, the processes screen is managing continue to run. You can then re-attach to the session at a later time, and your terminals are still there, the way you left them.

Screen also maintains individual, searchable scrollback buffers for each of the windows it manages. You can perform traditional “enter the search term and I'll find it for you” searches as well as incremental searches. This is such an obvious feature, it's surprising that more terminal emulators do not offer it.

Other notable features of screen are configurable key bindings, utf8 and multibyte charset support, multi-attach, configurable input and output translation, input and output filter, multi-user support with access control lists (ACLs) and logging.

Interacting with Screen

Before actually running screen, it's important to understand how to interact with it. Screen sends all entered text to the current window, with the exception of the command character. The default command character is Ctrl-A (press the Ctrl and the A key at the same time). The screen man page uses C-, Emacs style, to mean Ctrl-.

The command character is used to notify screen that you'd like to control screen itself, rather than the application in the current window. The key pressed after the command character designates which screen command you would like to perform.

Some of the more useful commands and their key bindings are shown in Table 1.

Table 1. Commands and Their Key Bindings

For many of the commonly used commands, the control version of the key is also bound to the command. An example of this is Ctrl-A C and Ctrl-A Ctrl-C to create a window.

To send Ctrl-A to an application without screen intercepting it, you can press Ctrl-A A. The command character can be changed to an alternate key if you wish. Typically Emacs users change the command character to Ctrl-B by adding escape Bb to their .screenrc. The following examples use Ctrl-A because that is the default.

As you might expect, .screenrc is the per-user configuration file in your home directory, and /etc/screenrc is the system-wide configuration file that applies to all users.

Window Basics

Now that you understand the fundamentals of interacting with screen, we can step through screen fundamentals using a typical screen session as an example. Probably the most typical use of screen is to control terminals on a remote machine on which you have a shell login.

So, for those of you playing along at home, log in to a remote host that has screen installed. If you don't have a remote host to ssh to, you can install screen and ssh to localhost. Packages for screen are available for most distributions.

You're now sitting at the shell prompt on the remote machine. Type screen at the prompt. You should see a splash screen showing some information explaining that screen is under the GPL, where to report bugs and so on. You can press the spacebar to bypass this screen (you can disable this splash screen permanently with startup_message off in your .screenrc). Next, you should arrive at another shell prompt, this one running inside of screen.

The new shell running inside of screen should behave like your first shell would. If you do a printenv, you may notice a few new environment variables set. Screen sets TERM to screen—each screen window provides its own vt100-compatible virtual terminal. The variable WINDOW is set to the virtual window number, and the variable STY is set to your session name. I'll explain more about those last two later.

So far, this single shell works exactly like you're used to working on a remote machine. For the sake of this example, say we are downloading the current version of screen (as of this writing, screen 3.9.13) from the screen distribution site at ftp.uni-erlangen.de/pub/utilities/screen. While this file is downloading, you decide to use your spare time to clean up your home directory. If you weren't using screen, you'd have to open another xterm and ssh to the remote machine. With screen, a simple Ctrl-A C will create a new screen window with a new shell process.

Thus far, you have an FTP client and a shell busily tidying up your home directory. You can check on your download in the original FTP window by using Ctrl-A P to go to the previous window. You can get back to your shell with Ctrl-A N.

When you check on your download, it's not finished (screen doesn't take that long to download, but we'll pretend it does for this demonstration). Time to get back to your messy home directory, right? Before doing that, press Ctrl-A Shift-M to monitor the current window for output. Now screen will notify you when there is activity in the FTP window. Bouncing between windows to check on your download's progress is no longer necessary. This also works in the inverse case; use Ctrl-A _ to monitor for silence (30 seconds by default). Monitoring for silence is useful for long compile jobs or other things that spew information.

You can continue to spawn new shells and do things in parallel on the remote machine. After you open a few windows, it becomes difficult to keep track of which window is where. This is where the windowlist comes in to play. Press Ctrl-A “, and you will be presented with a list of the current open windows. Navigate the list with the J and K keys. Pressing Enter on an entry will make it the current window. By default, the window name isn't all that descriptive. You can remedy this by setting the window name yourself with Ctrl-A Shift-A. You can set these titles automatically, much as you would set titles in an xterm, by sending Esc-K, then the title, then Esc-\. Most likely you can adapt a shell-specific recipe for setting the xterm titlebar to the screen window name using the mentioned escape sequences.

To finish up our basic run-through of windowing, let's close your existing windows. If you exit the shell that screen has spawned, the window is deleted automatically. You can delete a window manually with the kill command (default Ctrl-A K). When you exit all of the screen windows, screen exits. You also can tell screen to exit and kill all of your windows by issuing the quit command (Ctrl-A \).

Sessions

Now that you're creating new windows and bouncing around between them, you can get many things going in parallel. You could potentially have some editors, an IRC client and a few other things all running in their own windows. But occasionally disaster strikes, and your network connection dies (those of you still playing along at home can kill your SSH client). It looks like it's time to pick up the pieces and relaunch all of your applications on the remote machine, right? Not with screen.

Each time you start up screen without arguments, it creates a new session. This spawns two processes: a terminal management process and a client process. The client process automatically is “attached” to the terminal management process. When you type, the characters you enter go to the client, which sends them to the terminal management process, which then sends them to your application.

When your network connection dies, the client catches the signal and detaches from the terminal management process. The terminal management process continues along managing your terminals as if nothing happened. When you log back in, you can list running sessions by issuing screen -ls at the prompt. It should show something similar to the following:

There are screens on:
        24319.pts-9.hostname (Detached)
1 Sockets in /var/run/screen/S-youruserid.

This shows that your session automatically detached when your connection dropped.

You can re-attach to the session in a few ways. You can give a session name explicitly with screen -r sessionname. You can tell it to re-attach if possible, otherwise start a new session by running screen -R. Or you can go the “do whatever is needed to get a screen session” route and run screen -D -RR. This last option will detach already-attached clients and attach to the first session listed.

When you run one of these commands, you should be right where you left off before your network connection went down. When you're re-attached, you can continue working as if nothing ever happened.

It is also possible to attach to a session multiple times. This is useful if you haven't closed your screen session from another machine, or if you simply want to display windows from the same session side by side. You can multi-attach by adding an -x in the command-line options to screen when attaching.

Finally, when the end of the day rolls around and it's time to go home, you can detach from your session using Ctrl-A D. When you return the next day, you can re-attach, and you will be back where you left off.

Copy and Paste/Scrollback Mode

One of the key features listed in the beginning of the article was screen's searchable scrollback. This is a feature I could not live without. It's not immediately obvious to the new screen user, but screen's scrollback is accessed via the copy command. (You can enter copy mode with Ctrl-A [ or via the copy command.) Navigation works as expected with either the Arrow keys and Page Up/Down or the vi motion equivalents. Searching is accessed via either / and ? for vi-style search or Ctrl-S and Ctrl-R for incremental search. Case-insensitive search can be turned on with the screen command ignorecase yes. If you are using copy mode for scrollback only, it can be exited at any time with the Esc key.

To copy text, maneuver the cursor to the beginning of the desired text, and press the spacebar to mark it. Then position the cursor over the end of the text you'd like and press the spacebar again to mark it. When you mark the end, the text is copied into screen's internal copy buffer, and copy mode is exited. You can paste the text in your copy buffer into the active window with Ctrl-A ].

The final thing you should know about the copy and paste mode is the scrollback buffer is limited to 100 lines by default. This is, in my opinion, not enough. You can tweak this to a higher value (1,024 for example) by adding the command defscrollback 1024 to your .screenrc.

Opening Windows with screenrc

I have already mentioned that you can add a command to your .screenrc to change the behavior of screen. It's not immediately obvious, but you can put any screen command in a screenrc. This is very useful and can be used to spawn windows automatically with the screen command.

A typical application of this tidbit of knowledge is to launch a predefined set of windows at screen startup. Below is a sample screenrc that will do so:

# read in your normal screenrc
# before anything else
source $HOME/.screenrc
# now start opening windows
screen top
# it's possible to set the window title with
# the -t option
screen -t irc epic
# you can also specify the window number
# to launch in
screen -t mail 8 mutt
screen -t daemon 9 tail -f /var/log/daemon.log

If you save this to $HOME/.screenrc.multiwin you can tell screen to use it instead of your normal .screenrc by running screen -c $HOME/.screenrc.multiwin.

You also can launch more systems-oriented screen sessions from a startup script. A common application of a system screen session is a serial console server. Screen is well suited for this task because it has built-in support for serial terminals and logging. A commented example of a screenrc for this purpose is:

# This assumes that serialuser has proper
# permissions to access the serial ports and to
# write to the log files specified in the screenrc.
# turn logging on for all windows
deflog on
# tell screen to log to /var/log/serial.$WINDOW
logfile /var/log/serial.%n
# open windows on the serial ports
screen /dev/ttyS0 38400
screen /dev/ttyS1 19200

If you saved this file in /etc/screenrc.serial, you could launch it at startup with a script that runs:

su serialuser -c \
'screen -dmS serial -c /etc/screenrc.serial'
The -dmS serial options tell screen to launch the session in detached mode and name the session “serial”. User serialuser can log in and attach to this session exactly like any other normal screen session. Launching a detached screen also can be used to start screen from a cron job if this is preferred.

It is possible to set up a single system-wide screenrc that allows multiple users to connect to it. Screen supports multi-user mode with per-window ACLs that define what each user can and cannot do. Multi-user screen sessions, however, require that screen be setuid root. Because of this requirement, I am not going to include examples for multi-user screen sessions in an introductory article. If you would like to set up a multi-user screen session, read the screen docs, put on your “adding setuid root permissions to a complex piece of code” paranoia hat and be prepared to lock things down as tightly as possible.

As a third application, you could merge the two previous examples and launch system-wide interactive programs via screenrc. A good use of this would be launching mutella, a curses-based gnutella client, at startup. With screen, you can launch this program and connect to it on occasion to see the status, run queries, etc.

Further Information

You can find further information on screen in the screen documentation. The documentation is provided in both man and info format. I prefer the info format when browsing and the man page when searching for specific things, but that's a personal preference.

There are also a few on-line resources for screen users. First is Sven Guckes' screen pages at www.math.fu-berlin.de/~guckes/screen. Second is the helpful screen mailing list at groups.yahoo.com/group/gnu-screen. The mailing list is the first place you should go with questions after you have exhausted the available documentation. You must be subscribed to post.

Adam Lazur is a Linux consultant doing things ranging from embedded Linux to Beowulf clusters. In his spare time, Adam likes to write about himself in the third person. Adam welcomes comments about this article at adam@lazur.org.

__________________________


Special Magazine Offer -- 2 Free Trial Issues!
Receive 2 free trial issues of Linux Journal as well as instant online access to current and past issues. There's NO RISK and NO OBLIGATION to buy. CLICK HERE for offer

Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.

Sorry, offer available in the US only. International orders, click here.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

VIM remoting and screen

On May 9th, 2008 dkorah (not verified) says:

The article is super. Nice one.!

I came across this one while I was looking around for a solution for my vim IDE.

I am trying to create a vim + screen + bash wrap-up to make a vim IDE.

When I open a file, I fire off a delayed-open bash thread that does opening of files on a pre agreed vim server (say VIM_ON_SCREEN). Now while it is stuck in delay, I fire off a screen session with vim starting up the server (screen -R vim_screen vim --servername VIM_ON_SCREEN ) I expect the bash thread to kick in and remote-open files in the vim thats running in screen.

But it doesnt seem to work.

I did a bit of debugging. I started a screen session with vim and tried listing the VIM servers (vim --serverlist), but it didnt show up.

Any idea?

cursor keys and F-keys

On April 30th, 2008 y23 (not verified) says:

I use putty to log into the linux machine and use dosemu to run some old stuff I need...

but using screen stuffs up the keyboard... cursor keys or F keys.
setting putty to application mode.. I tried all combinations, but to no avail. Any light you guys can shed on this?

'Esc' on Vi becomes slower

On March 1st, 2008 antz (not verified) says:

When I open Vi or VIM while using screen, the 'Esc' takes time to be effective (though it is only a fraction of a second). Without screen, it is instantaneous (unless I have mappings starting with Esc).

Is there any setting I can make in my screenrc or elsewhere? It appears screen intercepts Esc and then perhaps waits for further input. Once that times out, it sends Esc to the running app.

'Esc' on vi becomes slower

On July 16th, 2008 tacitdynamite (not verified) says:

This is really bugging me too! I'm glad that you left this comment; I run screen + ratpoison, and wasn't sure which one was intercepting it. Vim + slow 'ESC' = sux. Any success ... anyone?

delay with 'esc' using vim and screen

On July 16th, 2008 tacitdynamite (not verified) says:

I figured out how to get rid of the delay; put the following:

maptimeout 0

in the .screenrc to make it not wait for more input characters. I added this for good measure:

defc1 off

because screen is essentially waiting for you to enter seven bytes after the 'esc' to enter in extended characters. Huzzah!

Renaming screen title

On February 24th, 2008 Arman (not verified) says:

Does anyone know if it's possible to rename a screen title if it wasn't set initially with the screen -t option?

Web Forms

Hi dear adam,

On April 14th, 2007 Sharad (not verified) says:

Hi dear adam,
really you have provided very good information about gnu screen,
even then I am facing a problem, So I found this page through
Google.

In side screen, if wanted to launch rsh to other machines in window,
then the typical command is
screen [-a] [-l] rsh machine # working fine.
but
If I wanted to run any other intractive program like vim, emacs, bash or zsh.
screen [-a] [-l] rsh machine zsh -il # no Control key working here.

I tried very some other flags also like -fa -fn etc, nothing worked.
and I did not got any clue in net.
Please let me know if this could be resolved.
thanks
Sharad

Named session

On March 30th, 2007 Anonymous (not verified) says:

Is there an easy way of naming a screen session, so that one could use easier-to-remember names with screen -r ? One way is to rename the named socket in /var/run/screen/. Wondering if there's a better way.

I just use a shell alias (I

On May 28th, 2007 Karthik Gurusamy (not verified) says:

I just use a shell alias (I have 'sr' -> for 'screen resume/recover'). At a time I have 1 or utmost two shell sessions (the second one is sr2). So never found the clumsy name as a big issue.

Karthik

Named Session

On April 10th, 2007 Anonymous (not verified) says:

Is there an easy way of naming a screen session, so that one could use easier-to-remember names with screen -r ? One way is to rename the named socket in /var/run/screen/. Wondering if there's a better way.

screen -S my_session_name

Renaming an existing screen session

On May 29th, 2008 David Keech (not verified) says:

You certainly can rename an existing screen session.

Type this from within the screen session you want to change:

ctrl-a :
sesionname newsessionname

and you session name will now be whatever you typed for "newsessionname".

The manual states that the $STY variable will not change and that this could cause some confusion. You can always change that variable yourself if it causes you a problem.

Hi

On March 21st, 2007 Anonymous (not verified) says:

Hi,

How to create command on Linux machine ? I have written one script . that file name is sysinfo_m .I want to make sysinfo_m file as command . Is it possible ? Please let me know

Thanks and Regards
Muthu

Inactive window bell notification

On December 16th, 2005 Roomservice (not verified) says:

Very good introduction, I suggested my buddies reading it.
I've been using screen for years in every day and there's a feature I would really like and miss the most:
A bell in a not active window should generate a bell (^G) in the active window as well instead of just writing this info out. If I could hear this notification I could react sooner to the problem.
Can this be set through the configuration or not?
I've read all the words in the long manual of this program, but...
Thanks.
RS

Oh! Shame! I've just found

On December 16th, 2005 Roomservice (not verified) says:

Oh! Shame! I've just found it in the man pages, sorry!!!

These lines in the .screenrc should make it:
bell_msg '^GBell in window %n'
activity '^GActivity in window %n'

RS

Alternative escape character: ^s

On July 21st, 2004 Anonymous says:

If ctrl-a isn't your bag, or you want to run screen in an ssh-ed screen I really enjoy using ctrl-s which AFAIK is mostly a legacy thing, but you've got to disable the default usage by putting the following maybe in a .bashrc or something:

tty > /dev/null && stty -ixon -ixoff

then in your .screenrc:
escape ^Ss

If it ever comes up you can always get an actual ctrl-s by doing two in a row.

Power Sessions with Screen

On May 23rd, 2004 Anonymous says:

I like a lot of other developers (presumably) use a windows box sometimes to log into my servers to do development and maintainence.

Before i knew screen i would open a putty session for each box i needed to work on. So for 6 servers i would have 6 putty running and it would soon clutter up my taskbar.

After i started using screen now I open one putty connection to the server1 and then just reattach the screen session. I do not even need to log into the other 5 servers.

This is a great time saver. Though I hope its not resource hungry for the servers to keep the screen session running,

I also found another project which tries to do what screen does check out sterm. It is a MDI window application.
Sterm
Its a freeware but its not GPL

Thanks,
sysadmim
Mortgage Fit

Re: Power Sessions with Screen

On February 13th, 2003 Anonymous says:

Been using this for about 5 years on SCO OpenServer5. Is very handy for serial terminal users who find the multiscreening a productivity improvement. The hot-keying between screens allows them reference back where they left off without having to 'back' out then select another option in the menus they use.

One problem I have found is the restricted range of ptys that are allowed in the version I have been supporting. It can only offer a maximum of 48 ptys. Also, if you have LAN connected devices you will find contention in the allocation of ptys. For instance both screen and telnet sessions use the ttyp0 - 8 range so you may find screen 'out of ptys' from time to time

Re: Power Sessions with Screen

On May 23rd, 2004 Anonymous says:

I like a lot of other developers (presumably) use a windows box sometimes to log into my servers to do development and maintainence.

Before i knew screen i would open a putty session for each box i needed to work on. So for 6 servers i would have 6 putty running and it would soon clutter up my taskbar.

After i started using screen now I open one putty connection to the server1 and then just reattach the screen session. I do not even need to log into the other 5 servers.

This is a great time saver. Though I hope its not resource hungry for the servers to keep the screen session running,

Thanks,
sysadmim
Mortgage Fit

Changing escape key sequence for screen.

On December 17th, 2002 Anonymous says:

There's a typo in the description of changing escape key

sequences.

the line to change it to escape Bb (for emacs users)

should read like this:

escape ^Bb

Personally, I find escape B handy in emacs, so I map the screen key to:

escape ^Zz

Re: Changing escape key sequence for screen.

On December 18th, 2003 Anonymous says:

I personally favor

escape ^Tt

because transpose-chars is a command I've used maybe twice in nearly a decade of Emacs, and everything else is bound to more useful things.

Re: Changing escape key sequence for screen.

On January 2nd, 2003 Anonymous says:

Between normal shell escapes and emacs navigation keys, many of the basic ctl-keys are pretty well utilized.

Ctl-Z for me is critical for suspending processes.

I prefer, 'escape ^Gg' since who really wants to generate a random bell anyway :)

Re: Changing escape key sequence for screen.

On February 9th, 2004 Anonymous says:

Far better is to use vi which doesn't require the use of control/meta keys!

Re: Changing escape key sequence for screen.

On August 25th, 2003 Anonymous says:

C-g is also critical for canceling commands...

Re: Changing escape key sequence for screen.

On August 25th, 2003 Anonymous says:

Alternatives include:

escape ^Oo (C-o opens a new line in emacs)
escape ^Pp (C-p moves the cursor to the previous line)

Re: Changing escape key sequence for screen.

On July 7th, 2004 Anonymous says:

Five years ago my screen escape and literal command characters of choice for Emacs noninterference:

escape "^^^^"

Using Ctrl-^ was a bit awkward but I got used to it. If I were using screen as much nowadays I'd probably choose a different character, maybe even a function key.

The first thing I looked for

On August 29th, 2005 sqweek (not verified) says:

The first thing I looked for when I started using screen was an option to change the escape key - I didn't fancy having to hit C-a a to move to the start of the line.
After thinking about it for a while, I came up with this:
escape `\'
Which I'm a big fan of. For some reason hitting ` ' to get a backquote just feels intuitive (though it might help that I use dvorak so ' is where q is on qwerty).

Sessions for X

On December 7th, 2002 Anonymous says:

I love screen. But what I want is something that can do stateful sessions with X programs when my X server crashes. VNC is to slow, and Xmove I couldn't get to work. Any suggestions?

My address is davidmccabe ta myrealbox tod com

if you'd like to contact me about that.

Thanks!

Re: Sessions for X

On December 8th, 2002 Anonymous says:

have you looked at ratpoison? (http://ratpoison.sourceforge.net)

I thought I remember reading somewhere that you could detach and attach

sessions...but I can't seem to find it documented anywhere now. Anyway,

if you like screen, you might like ratpoison.

Re: Sessions for X

On December 14th, 2002 Anonymous says:

Yes, I use Ratpoison right now, and no, it doesn't do that.

Re: Sessions for X

On December 8th, 2002 Anonymous says:

http://palm.freshmeat.net/articles/view/581/

Featured Videos

Linux Journal Gadget Guy, Shawn Powers, reviews the Flip Video Ultra, a small portable video camera, and shows us how easy it is to edit the video with Kino.

Thanks to our sponsor: Silicon Mechanics

Webcams are notorious for their lack of support under Linux. But thanks to GSPCA, many webcams now have functional V4L drivers. This tutorial covers the building, installation, and configuration of the GSPCA drivers, including how to adjust color balance and brightness directly at the kernel module level.

From the Magazine

September 2008, #173

Feeling a bit like a Thermian? Never give up, never surrender! Someday, you could go from underdog to top dog. Just take a look at a few of the underdogs we highlight in this issue: Mutt, djbdns, Nginix, Gentoo, Xara and the program voted mostly likely to fail just a few years back—Firefox. If Firefox not radical enough for you, check out Chef Marcel's column for some more alternatives. Having trouble mapping your program data to your relational database? If so, Rueven Lerner shows you some tricks in his At The Forge column.

Need to run GUI applications on your server in the next state? In his Paranoid Penguin column, Mick Bauer shows you how to do it securely. Kyle Rankin keeps hacking and slashing and shows you a few split screen secrets you may not be familiar with. Finally, we all know what happens next February, but only Doc knows what happens afterward.

Read this issue