Power Sessions with Screen

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 \).

______________________

Comments

Comment viewing options

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

screen -- window notification

rask's picture

1. Connect to the remote machine via ssh.

Terminal settings is fine.

2. screen

When I do that, then all my terminal settings change. For example, now I get window notification (not a bell but flash). How can I switch "flash notification" off ?

thanks.

screen. THX

Anonymous's picture

Never heard about screen. THX untile I saw this
very intressting info thank for explaing .
Visit clownsilver

comment

seo india's picture

Thanks for the trackback on my photo of frijole! For those interested, I have lots of photos from the opening.
Hot Rolling Mills

Stucki - u r great

Anonymous's picture

Sorry for being out of context.
Was getting error "can not open /dev/tty", while executing a perl script using ssh.

After "-t" option it went away..incase if its useful for some soul.

Status Bar Line

Michael M.'s picture

Screen quickly becomes confusing for me (since it's by default indistinguishable from a normal terminal), so I use the hardstatusline setting in my .screenrc:

hardstatus alwayslastline
hardstatus string '%{gk}[ %{G}%H %{g}][%= %{wk}%?%-Lw%?%{=b kR}(%{W}%n*%f %t%?(%u)%?%{=b kR})%{= kw}%?%+Lw%?%?%= %{g}][%{Y}%l%{g}]%{=b C}[ %m/%d %c ]%{W}

What that crazy line displays is this: On the last line:

  1. your hostname (the name of the computer you're working on. This is useful if you ssh into many computers, and run a screen in each. You can even do nested screen sessions: Use C-a + a + __ instead of C-a + ___
  2. A listing of all the screen windows you have open, and indication of which you're currently on. This is useful for navigating between windows. By default they aren't helpfully named (e.g. "5$ bash"), but you can rename them with C-a + A, and then something like "python.
  3. System Load (I find it useful, not everyone will.
  4. Date, Time


[mike][ 0-$ emacs (1*$ python) 2-$ vim [0.06 0.12 0.53][ 06/29 5:19]

acai berry cleanse reviews

Anonymous's picture

acai berry cleanse reviews - There are many other essential acai berry supplements in Acai Berry - like phosphorus, iron, calcium, potassium, Vit-B1, Vit-B2, Vit-B3, Vit-C, and Vit-E - minerals and vitamins that are important for the sound functioning of your body.

re acai berry during screen session

Anonymous's picture

Weird. When I consumed this acai berry supplement during a screen session, I farted once.
Farting was increased during multiple screen session.

Use wordpress tags

Anonymous's picture

Use Tags There are some other aspects of tagging. Presentation of tags can be influenced by tag similarities and tag hierarchy ( if there is any)

Hi Adam, this is a nice

affenzahn's picture

Hi Adam,

this is a nice article about screen. THX a lot. I have a question and hope you can help me.
I use screen since some time to start ssh session automatic.

- screen -t session1 1 ssh root@system1

It works. But I need a behaviour which didnt' close the screen session when exit. I want stay on the bash after exit and have the ssh command in the bash history.
Is it possible to handle this with screen ?

Cheers

Adam

bind keys in screenrc

Anonymous's picture

How to change CtrA+p for previous and CtrA+n for Next window. I do not want to repeat these option oftenly, i want options just as

Ctr+-> (Right arrow) for Next
Ctr+<- (Left arrow) for Previous.

have you looked at ratpoison?

beyli's picture

very nice images ...........

run same command on multiple sessions

samsixtyone's picture

is there any way, to run same command on all curently opened screen session?

thx

müzik dinle's picture

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.

of course.. you can use

Lo0m's picture

of course.. you can use screen -S name or (inside running session) - Ctrl+A :sessionname name

why

yarışma's picture

why
?
bell_msg '^GBell in window %n'
activity '^GActivity in window %n'

Personally, I find escape

oyun sitesi's picture

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.

Screen is Great!

Jeff at Rackaid's picture

I use screen all of the time. I've long touted the benefits of using it for long running processes. I also use it interactively when reviewing actions of staff. My favorite use is to launch it when I have to run an errand, go home, go to lunch, etc. I can come back and pick up where I left off with worrying about a remote terminal session being open on my system.

Between normal shell escapes

lida's picture

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 :)

Power submit

John78's picture

To the poser above - Instead of VNC which I have also found really slow, try using chat. It allows users of Microsoft Windows to connect to remote Unix computers, run graphical applications and have the graphics displayed on their desktops.

Oh! Shame!

çok güzel hareketler bunlar's picture

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

Webumut

Webumut's picture

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'
http://www.webumut.com

ttt

sagliksorunlari's picture

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

^A + A (control A then

Anonymous's picture

^A + A

(control A then capital A)

renaming a running session

Nate922's picture

use screen -ls to get the session ID numbers. then just:


screen -X -S sessionname

didnt copy right

Nate922's picture

my above comment didnt complete:

screen -X -S {session#} sessionname {new session name}

Thank you

MorningMist's picture

I just wanted to say thanks for adding that cause you just saved me lol. :D

This is a great

Misafir's picture

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

Fwd: GOOD MORNING :)

vector graphics's picture

[...] Google redefines disruption (via @Valuecruncher) – Fascinating read on Google’s mobile and mapping developments. [...]

hi

amatör's picture

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?

session on x

rkms's picture

A very informative article. Loved reading it. In fact I have used screen to connect to my linux machine at my office. One thing though is that it is a console oriented beast.

To the poser above - Instead of VNC which I have also found really slow, try using XLiveCD. It allows users of Microsoft Windows to connect to remote Unix computers, run graphical applications and have the graphics displayed on their desktops.

rkms
Linux and friends

VIM remoting and screen

dkorah's picture

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

y23's picture

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

antz's picture

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

tacitdynamite's picture

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?

Use Ctrl-C instead of Esc in Vim

Saganist's picture

Another solution is to use Ctrl-C in Vim instead of Esc. It works just the same. It took me a while to get used to it, but I like it a lot better than Esc now.

delay with 'esc' using vim and screen

tacitdynamite's picture

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!

Hi dear adam,

Sharad's picture

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

screen [-a] [-l] rsh machine zsh -il (NEVER WORKS!)

stucki's picture

Hi!

I stumbled upon your question searching
for another screen-problem :-)

Your problem is NOT 'screen' but 'rsh'!
There are TWO modes of running remote commands:
1) interactive(login) as 'rsh machine'
2) command(one run) as 'rsh machine program'

(1) gets a 'terminal' which can react on control and
other single keystrokes
(2) only gets a 'pipe' (simple input output), so it can
NEVER react correctly on control chars and especially
NEVER run things like an interactive editor.

'rsh' is normally replaced by 'ssh' now,
and THAT has an option '-t' (Terminal)
which exactly solves the problem!

try 'ssh -t machine vim filename' ...

Stucki

Named session

Anonymous's picture

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

Karthik Gurusamy's picture

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

Anonymous's picture

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

David Keech's picture

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.

Inactive window bell notification

Roomservice's picture

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

Roomservice's picture

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

Been using this for about 5

Anonymous's picture

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 laptop battery having to 'back' out then select another option in the menus they use.

Alternative escape character: ^s

Anonymous's picture

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.

Re: Power Sessions with Screen

Anonymous's picture

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

Changing escape key sequence for screen.

Anonymous's picture

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.

Anonymous's picture

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.

Anonymous's picture

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 :)

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState