Screen: Usage and Technique

Who should use this document? Anyone wishing to learn how to use or become more competent with screen
Purpose of this document To demonstrate effective basic and intermediate use of screen.

Last modified: 01 Jun, 2007

What is screen? Screen is a curses-based, full-screen window manager and terminal multiplexer which allows any number of windows (i.e. processes) to be mapped onto a single terminal, or terminal emulator, or Linux VT. It is the ultimate power tool for working efficiently over an ssh connection, or in any other situation where X is not available.

Crash Course

To start screen, type 'screen -D -R' at the command line.

All screen command keys begin with the prefix, which is Control+a (hereafter C-a). Screen commands are case-sentitive.

The command to spawn a new window containing a fresh shell is C-a c (that is, press C-a, release, and press c).

To see a quick list of windows, do C-a w. It will appear at the bottom of the terminal window (or in the titlebar of the window) and will look like this:

  foreach my $file (@files) {
    $img->read(file => $file)
      or next;
  0$ bash  1*$ emacs  2$ irssi  3-$ bash  4$ ssh

In the window list, the current window is indicated by an asterisk between the window number and the dollar sign. The previously active window is indicated by a hyphen in the same location.

To jump between the current and previously active windows, do C-a C-a. To jump to a specific window, do C-a <n>, where n is the number of the desired window.

One of screen's most useful features is the ability to detach a session from its controlling terminal, leaving all programs running and awaiting the user's return. The command to detach is C-a d. To reattach to a detached session, type 'screen -D -R' at the command line (the same command used above to start a session).

To exit screen entirely, terminate all processes running under its control.

Window Handling

Though many people don't think of it as such, screen is a window manager. As such, it devotes a lot of time, effort, and commands to the management of windows.

Opening

On startup, by default, screen creates a single window containing an instance of a login shell. As mentioned previously, C-a c will spawn a new window containing a new shell.

To create a window which contains a program other than a shell, launch the desired program from an existing shell, but prefix the usual command with 'screen', as in:

  deneb:~$ screen irssi -c irc.us.slashnet.org

This doesn't create nested screens ; it creates a new window which contains an irssi process — without an underlying shell, saving memory and PTY overhead.

It is possible to create keybindings which will open new windows containing instances of specific programs, and to have sets of windows created at startup. These functions will be covered in the Customization section.

Closing

Windows close automatically when the program they contain terminates, so the usual way to close a window is to exit the program which is running inside it.

If a program becomes unresponsive, it (and its window) can be killed with C-a K.

When a window is closed, the numbers of windows "above" it are not adjusted. Instead, a gap is left in the window list which will be filled by the next new window.

Switching

  foreach my $file (@files) {
    $img->read(file => $file)
      or next;
  0$ bash  1*$ emacs  2$ irssi  3-$ bash  4$ ssh

It has been mentioned that C-a C-a will flip between the currently active and previously active windows. In the example above this means switching from window 1 to window 3 (and back, etc.).

C-a p switches to the previous window in the list (not the previously active window), and C-a n switches to the next window in the list. Referring to the example again, the previous window is 0 and the next window is 2. For the purposes of the previous and next commands, the window list is circular; previous from 0 is 4 and next from 4 is 0.

C-a <n> jumps immediately to window n, where n is a number between 0 and 9.

Windows numbered 10 and up must be accessed through the full windowlist, accessed via C-a " (Control+a, doublequote). The list looks like this:

Num Name                                              Flags
  0 bash                                                  $
  1 emacs                                                 $
  2 irssi                                                 $
  3 bash                                                  $
  4 ssh                                                   $

Use the up and down arrow keys to move the highlighted line, and the Enter key to select the window to switch to.

Splitting

Screen mostly wants to keep things full-screen, but it does have limited multi-display capabilities. The display starts out with one region (the whole window). Each time C-a S is pressed, a new region will be added and the display will be split horizontally among the regions. One press splits the display into halves; a second press splits it into thirds, a third into fourths, and so on.

Newly spawned regions are empty; switch the input focus to one with C-a TAB and then select a window for it to display.

Remove the current region with C-a X. Remove all regions but the current region (return to full-screen) with C-a Q.

Removing regions does not destroy the windows they display. Regions are viewports to windows, not windows themselves.

Regions can be resized, but there are no keybindings for this by default. The command is resize; see the manpage for more information.

Vertical splits are not possible.

Miscellaneous

The title of a window may be changed at any time by doing C-a A, which will prompt for the new title.

Screen has a copypaste facility which enables the copying of text from one screen window to another. Press C-a [ to enter copy mode. The cursor will become free-moving; place it at the beginning of the desired selection and press Enter. Move it to the end of the selection (which should be highlighted as it is selected) and press Enter again to complete the selection. Paste with C-a ].

Sessions

As useful as screen's windowing capabilities are, their utility would be severely diminished without the session-handling functions that go alongside. A session in screen is very much like a session in Firefox: a collection of open windows.

Detaching

A running screen session can be detached with C-a d. This will cause control to revert back to the shell from which screen was launched. A message like this one will be printed:

  lyra:~$ screen -D -R
  [detached]
  lyra:~$ 

Programs in a detached session are not terminated, halted, or asleep; they continue running just as if they were connected to a live terminal (because they are: the back-end screen process).

Most handily of all, sessions are (or at least should be) automatically detached if the connection from the user's terminal to the server screen is running on is lost.

Reattaching

There are several ways to reattach to a session, involving the -d, -D, -r, and -R options in various combinations, but one which is guaranteed to work is 'screen -D -R'. This invocation will attach to whatever session can be found, detaching an attached session if neccessary, logging out remotely if needed, and even spawning a new session if one does not exist.

It is possible to find existing sessions with:

lyra:~$ screen -ls
There is a screen on:
        15032.pts-99.lyra      (Detached)
1 Socket in /tmp/uscreens/S-mdxi.

lyra:~$

This is handy in the event of multiple detached screen sessions existing. It will allow the graceful and clean shutdown of any/all sessions by attaching to specific sessions, as in:

lyra:~$ screen -r 15032.pts-99.lyra

But if 'screen -D -R' is always used to start screen and/or reattach to a session, this will never be neccessary.

Locking

Screen can lock its terminal via C-a x. This does not lock the machine, or X, it merely puts a password prompt "in front of" the screen session, rendering that terminal useless until the user enters their password.

Multiview and Multiuser

It is possible to be attached to the same screen session from multiple terminals simply by attaching normally from the initial terminal and with screen -x from all others.

In this mode, each view of the session has independent control (i.e. switching windows in one view does not switch the window of the other view). But there is only one cursor for each window, with control being shared and concurrent between all views (i.e. any number of people can type in a single editor session, but all characters go to the same place; there are no independent edit points as in SubEthaEdit).

By default, screen only allows the session owner to attach. This can be changed by issuing the multiuser command and setting up passwords and ACLs for other users who should be allowed access. This is beyond the scope of this document .

Customization

Screen, like all good tools produced by nerds for nerds, is heavily customizable. Here are some of the ways it can be shaped and molded.

screenrc

Semipermanent customizations are made through screen's dotfile. The per-user file is ~/.screenrc and the system level file is /etc/screenrc.

The screenrc file is very much like a shell script: a list of commands, one per line, which are executed one after the other.

Commands

Many screen commands are pre-bound to keys, but many others are not. The majority of these are environment modifiers or settings, and they are accessed by typing C-a :, which will move the cursor to a minibuffer at the bottom of the window where long-form commands can be typed.

Everything which follows can either be executed interactively after typing C-a : or by entering them into a screenrc file.

Keybindings

A very useful customization is to define custom keybindings with the bind command. The basic form is 'bind [key] [command]'. Here are some examples:

# make some shortcuts for spawning favorite apps
bind W screen -t w3m w3m google.com
bind E screen -t emacs emacs
bind I screen -t irc irssi -c irc.us.slashnet.org

Keys can be unbound with a bind which has a null [command] portion:

# rebind 'kill window' from C-a k to C-a K
bind k
bind K kill

One special binding is the prefix or escape key (C-a by default). It is not changed with bind, but with the escape command.

# change the prefix to C-z and make 'C-z z' send a literal C-z
escape ^Zz

Startup Windows

To spawn a given set of windows at startup, end .screenrc with a list of screen commands.

# from my personal .screenrc on my home server
screen -t irc 0 irssi
screen -t olive 1 olive
screen -t aim 2 pork

The numbers between the window title argument and the command to be run specify explicit window numbering. This is neccessary if you want the same programs to be in the same windows everytime — without them, windows will be numbered as their programs become responsive (the order of which is nondeterministic).

Status Line

Screen has a feature called the hardstatus line which constantly displays information about the running session.

Some people like to have the hardstatus always be in the bottom line of their terminal. This can be done with the commands:

hardstatus on
hardstatus alwayslastline

The hardstatus displays the hardstatus string, which is arbitrary. For a cute Google logo, try

hardstatus string "%{wk}[%{B}G%{R}o%{Y}o%{B}g%{G}l%{R}e%{w}]%{.d}"

It is, of course, possible to craft slightly more useful status strings.

# greyscale window list with datetime at right
hardstatus string '%{= dK}%-Lw%{= dW}%50>%n%f* %t%{= dK}%+Lw%< %{= kG}%-=%D %d %M %Y %c:%s%{-}' 

# colored window list with system stats
hardstatus string "%{wk}%{kW}|%{-} {%{Yk}%D %m-%d-%y%{-} %{Wk}%C%a%{-}} {%{Gk}%H%{-} %l} %{kW}|%{-}%{wb} %-w %{Wr}[%n %t]%{-} %+w%=%{kW}|%{-}"

The full specification for hardstatus strings can be found in screen's manpage, in the STRING ESCAPES section.

To get back the terminal line which hardstatus eats, do 'hardstatus ignore'.

Miscellany

Troubleshooting

One of my shell windows has become unresponsive!
Try doing C-q; you may have accidentally hit C-s instead of C-a.

C-s is the ASCII control character for XOFF (as in XON/XOFF transmission control). C-q is XON and will fix the problem if this is the case.

Tips and Tricks

Time and Loadavg
C-a t will display the current time, date, and loadavg of the machine screen is running on.
Digraphs (Compose Mode)
Screen was originally written by a German, and has a strong heritage of European contributors and users, so it is unsurprising that it has a built-in mode to allow the composition of digraphs (accented characters). Do C-a C-v and then type the characters you wish to compose.
Examples
  a + " → ä
  o + / → ø
  n + ~ → ñ
Be aware that if screen's terminal or its fonts are not set up properly, you may see garbage, see nothing at all, or generate control characters by doing this.
Nethack Mode
Release your session's inner barbarian with 'nethack on'. This will change screen's error messages to something a bit more arcane than usual.
Questions, comments, suggestions and flames to <sboyette@gmail.com>.