Rate this page del.icio.us  Digg slashdot StumbleUpon

A guide to GNU Screen

by

written by Steve ‘Ashcrow’ Milner and Anderson Silva

The same way tabbed browsing revolutionized the web experience, GNU Screen can do the same for your experience in the command line. GNU Screen allows you to manage several interactive shell instances within the same “window.” By using different keyboard shortcuts, you are able to shuffle through the shell instances, access any of them directly, create new ones, kill old ones, attach and detach existing ones.

Instead of opening up several terminal instances on your desktop or using those ugly GNOME/KDE-based tabs, Screen can do it better and simpler.

Not only that, with GNU Screen, you can share sessions with others and detach/attach terminal sessions. It is a great tool for people who have to share working environments between work and home.

By adding a status bar to your screen environment, you are able to name your shell instances on the fly or via a configuration file called .screenrc that can be created on the user’s home directory.

Installing

Installing Screen on a Fedora or Red Hat® Enterprise Linux® 5 system is quite easy with yum, assuming you have sudo access.

  1. Login as root:
    su # enter root password
  2. Use yum to install it:
    yum install screen

Enter your password. After a few minutes (depending on your network connection), Screen will be installed. But before you start playing around with it, let's look at how to do some basic configuration.

Customizing the configuration file

Screen keeps its configuration file in the same vein that many applications do: in a dot file in your user's home directory. This file is aptly named .screenrc. In my experience, most people use ~/.screenrc to do two things:

  • Make a hardstatus line. This is basically a line at the bottom of the screen that lists your current terminal and all opened ones. It can also display the system clock and the hostname.
  • Default screens on startup. It's quite nice to have your IRC connection, mail client, and default SSH connections auto-start for you!

The lines below are numbered for reference. Your config file should not have numbered lines.

1 hardstatus alwayslastline
2 hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{=kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B}%Y-%m-%d %{W}%c %{g}]'
3
4 # Default screens
5 screen -t shell1	0
6 screen -t shell2	1
7 screen -t server	2	ssh me@myserver

On lines 1 and 2, you are setting the hardstatus. Line 1 makes the hardstatus always show up as the last line. Line 2 is about what will be shown in the hardstatus line. In this case you will see something like so at the bottom:

As you change screens, you will see the parentheses move around the active screen.

Line 4 is a comment, as it starts with #. Lines 5-7 are all screen statements in the following format:

	screen -t NameOfScreen ScreenNumber ShellCommand

Shortcuts

The following are some of the most used shortcuts that lets you navigate through your screen environment. Note that unless modified by your .screenrc, by default every screen shortcut is preceded by Ctrl+a. Note that these shortcuts are case-sensitive.

  • 0 through 9 – Switches between windows
  • Ctrl+n – Switches to the next available window
  • Backspace – Switches to the previous available
  • Ctrl+a – Switches back to the last window you were on
  • A – Changes window session name
  • K – Kills a window session
  • c – Creates a new window
  • [ - Then use arrows to scroll up and down terminal

Find out about more shortcuts in Screen's man pages. In your terminal, run: man screen.

Sharing a session with others

Another great application of Screen is to allow other people to login to your station and to watch the work you are doing. It is a great way to teach someone how to do things on the shell.

Setup to allow screen to be shared

  1. As root: chmod u+s /usr/bin/screen (Screen has to be SUID if you want to share a term between two users.)
    Note: SUID allows an executable to be run by the owner of that file, instead of with the user's own permission. There are some security concerns when doing this, so use this tip at your own discretion.
  2. chmod 755 /var/run/screen
  3. Log out of root, and run Screen as the user who is going to share the session:
    screen

  4. Press Ctrl+a, then type :multiuser on and press Enter.
  5. Press Ctrl+a, then type :acladd steve (”steve” is the username of the person who will connect to your screen session).

Connecting to the shared screen:

  1. SSH into the workstation that you are going to watch the screen session on.
  2. On your terminal type: screen -x anderson/ (”anderson” is the username of the person who is sharing the screen session. You need the / at the end.).

And now both users (from the host and guest) will be sharing a screen session and can run commands on the terminal.

Working from multiple locations

Let's say you have a screen session open at work with X number of windows on it. Within those screens you may be running an IRC client, an SSH connection to the web server, and your favorite text-based email client. It's 5 p.m. and you have to go home, but you still have work left to do.

Without Screen you would probably go home, VPN into your company's network, and fire up all the shells you need to keep working from home. With Screen, life gets a little easier.

You can simply SSH into your workstation at work and list your available screen sessions with the command:

screen -ls

And connect to the sessions you were running at work with the command:

screen -x screen_session_name

This way screen will let you pick things up exactly from where you left off.

Applications to make Screen your window manager

Now that you have seen what Screen can do for you, you probably are wondering how to make it your main interaction point, like a terminal window manager.

Let's start with IRC, a very common and popular chat system. Instead of using a graphical client like Pidgin, install Irssi. Irssi sports a slick console interface, tons of add-ons and scripts, and can be enhanced with Perl. It's even theme-able!

Another important part of any user's setup is email. Today most people use graphical clients such as Thunderbird, Evolution, or Sylpheed. My favorite client happens to run in a terminal: Mutt. While Mutt isn't the easiest client in the world to set up, it sure is a joy to use. You can even use your favorite console text editor for doing emails.

Speaking of favorite text editors, there is a good chance that you work on some code projects or configurations. Instead of using gedit/kedit or powering up a heavy IDE such as Eclipse, you can pick up on Vim. Vim is a powerful text editor which, as is stated on the Vim website, could be considered an entire IDE in itself and sports syntax coloring in over 200 programming languages. If Vim doesn't fit your style, there is always emacs, nano, or JOE.

Now all you need you need to do is edit your ~/.screenrc to meet your needs.

My ~/.screenrc looks like the following:

	1 hardstatus alwayslastline
	2 hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{=
kw}%?%-Lw%?%{r}(%{W}%n*%f %t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B}
%Y-%m-%d %{W}%c %{g}]'
	3
	4 # Default screens
	5 screen -t shell1	0
	6 screen -t shell2	1
	7 screen -t server	2 	sh me@myserver
	8 screen -t IRC	7	irssi
	9 screen -t Mail	8	mutt

Once you get used to the shortcuts in GNU screen, not only will your desktop become more organized (due to the lower number of open windows), but your efficiency as a developer or system administrator will increase not only at work but at your home office as well.

54 responses to “A guide to GNU Screen”

  1. Style » A guide to GNU Screen says:

    [...] veryvera wrote an interesting post today onHere’s a quick excerptIf Vim doesn’t fit your style, there is always emacs, nano, or JOE. Now all you need you need to do is edit your ~/.screenrc to meet your needs. My ~/.screenrc looks like the following: 1 hardstatus alwayslastline 2 hardstatus string … [...]

  2. Itsyaw.Com » A guide to GNU Screen says:

    [...] unknown wrote an interesting post today on A guide to GNU ScreenHere’s a quick excerpt [...]

  3. Dmitriy Kropivnitskiy says:

    Yeah, I gave screen a try several times. The problem is, I use CTRL-A for “go to beginning of the line” a lot and all the screen shortcuts seem to utilize CTRL-A.

  4. Al Tobey says:

    Dmitriy, you can use Ctrl-a by hitting Ctrl-a-a.

    I also use “set -o vi” which works in bash, ksh, and pretty much any shell with POSIX mode. vi mode lets you operate your shell using keyboard commands similar to the vi editor. To get back to the default emacs-style, use “set -o emacs”.

  5. Anderson Silva says:

    Dmitriy Kropivnitskiy,

    Add the following line to your .screenrc

    escape ^gg

    Now, you can use Ctrl+g instead of Ctrl+a, Steve uses ~

    You can customize it to whatever key you want.

    I hope this helps.

    AS

  6. Style » Comment on A guide to GNU Screen by Style » A guide to GNU Screen says:

    [...] mauzenne wrote an interesting post today onHere’s a quick excerptveryvera wrote an interesting post today onHere’sa quick excerptIf Vim doesn’t fit your style, there is always emacs, nano, or JOE. Now all you need you need to do is edit your ~/.screenrc to meet your needs. My ~/.screenrc looks like … [...]

  7. Style » Comment on A guide to GNU Screen by Style » Comment on A guide to … says:

    [...] jstruan wrote an interesting post today onHere’s a quick excerptmauzenne wrote an interesting post today onHere’sa quick excerptveryvera wrote an interesting post today onHere’sa quick excerptIf Vim doesn’t fit your style, there is always emacs, nano, or JOE. Now all you need you need to do is edit … [...]

  8. Ted Roche’s weblog » Red Hat Magazine | A guide to GNU Screen says:

    [...] A handy reference, A guide to GNU Screen, appears inRed Hat Magazine: The same way tabbed browsing revolutionized the web experience, GNU Screen can do the same for your experience in the command line. GNU Screen allows you to manage several interactive shell instances within the same “window.” [...]

  9. Brian says:

    I have customized my bash shell fairly heavily – changed prompt, vi style keystrokes, bash completion etc etc etc.
    How do I get screen to pick up on all those settings?

  10. HowTo - gnu screen | Linux Brain Dump says:

    [...] I’ve been meaning to write a guide to using GNU screen for months now, but it seems that Steve ‘Ashcrow’ Milner and Anderson Silva beat me to it. [?] Share This [...]

  11. links for 2007-09-29 « The Wayward Word Press says:

    [...] Red Hat Magazine | A guide to GNU Screen Screen is a great tool, a valuable addition to your Linux toolbox (tags: open-source linux programming-tools via:lxer) [...]

  12. a.kao » A guide to GNU Screen says:

    [...] read more | digg story [...]

  13. Bryn says:

    > I have customized my bash shell fairly heavily – changed
    > prompt, vi style keystrokes, bash completion etc etc etc.
    > How do I get screen to pick up on all those settings?

    You don’t need to – screen doesn’t replace your shell so any changes you make to the shell environment via e.g. bashrc or bash_profile will still be applied inside screen.

  14. Brian says:

    > You don’t need to – screen doesn’t replace your shell so
    > any changes you make to the shell environment via e.g.
    > bashrc or bash_profile will still be applied inside screen.

    Unfortunately that doesn’t hold true here… On my OSX box it doesn’t pick up anything, on my typical linux boxes it brings forward the bash prompt but not the vi style keybindings.

  15. abeowitz says:

    Any way to send one command to all screens at once?

    In other words, open sessions to a bunch of separate machines and instead of C-a,n “ps”, C-a,n “ps”, … Issue the command once, and C-a,n to view the output in each?

  16. BigFill says:

    Hardly revolutionary. Yawn! Ugly tabs? Is that a line from a marketing brochure?

  17. Mohammad Bahathir Hashim says:

    Beside dettach and reattach feature, I also love the “split” feature. Even better, latest development version, can do vertical split too. With the feature, I can monitor several items at the same time, example, irssi at the top pane, top at the middle and mutt at bottom. Oh, wait, nethack is hiding behind :)

  18. Jim C says:

    I was introduced to screen about 4 years ago, and haven’t looked back. It’s brilliant, and has more features than I could imagine using, but am gradually finding new ways to use them.

    I don’t think BigFill ‘gets it’. Sure, you could open up multiple windows in X11 (or in PuTTY if you’re a Windows user) to do your job. But consider this: What do you do if your network connection between your laptop/workstation and the machines you’re working on gets interrupted (eg, working from home over VPN)? Basically you have to set everything up again.

    But with screen, you ssh to a remote host, set up screen with as many virtual windows as you need, and if the connection between you and the screen session gets interrupted, no problem, just get your VPN going again, ssh to the remote host, then “screen -rd” (or “screen -rd “) and you’re back where you were moments earlier. This may not make complete sense until you’ve actually tried it.

    This approach is also handy if you want to disconnect at 5pm and head home to continue from there. Or simply to reconnect and resume the next morning without having to do session setup situps.

    If you prefer the GUI approach, there’s always VNC, but quite often the command line is where all the goodness happens.

    Earlier tonight I realized that I’d like to write a couple scripts, each one which will fire up a new screen session (completely separate from any other I might be running), but from the context of the script in question, there will be multiple commands where each command connects to a different screen windows. I think I’ve figured out a way to do this from reading the man page earlier tonight, although it’s not explicitly called out as such.

    Anyway, happy screening all!

  19. tj says:

    I have RH3 and screen install fine from RH rpm. Screen works except multiuser mode. The instructions require that for multiuser mode we must do “chmod 755 /var/run/screen” however this file/directory does not exist on my system.

    Next I activate multiuser mode and acladd the desired user. When this user tries to connect to my screen they get the error to the effect that “/tmp/screen-[my user name]” does not exist, which is correct, this file/directory does not exist. Creating it as a file simply results in the error “here is no screen to be attached matching [my user name]”

    Any assistance appreciated

  20. Sitaram Chamarty says:

    Screen is great, but please don’t use it for sharing sessions.

    Use “kibitz” from the “expect” package instead. None of the one-time (SUID, etc) or every-time (multiuser, acladd, screen -x) complexities described above.

    When userA types “kibitz userB”, userB will see:

    Message from userA@our.dom.ain on pts/1 at 15:59 …
    Can we talk? Run: kibitz -28996

    All he has to do is type the command and they are sharing userA’s session. Either of them hits a Ctrl-D to end the shared session.

    Can’t get simpler than that…

  21. Richard says:

    Just like abeowitz, I’m wondering whether it is possible
    to use screen to send commands to multiple screens.

    According the documentation this should be possible with
    the “at” command, but I don’t get it to work.

    So the command sequence:
    C-a :at # date
    Should result in a date executed on all windows (to my
    understanding, but the result I get is:
    “: at: at least two arguments required”)

    OTOH according the TODO file at:
    ftp://ftp.uni-erlangen.de/pub/utilities/screen/screen-4.0.3.tar.gz
    states: “- type into several windows at once (for cluster admins)”
    That file has been changed in august 2003 for the last time… :(

    Hopefully someone reading this article knows how to use the
    at command???

  22. Hey Richard! says:

    With the ‘at’ command, you can send commands to other windows that have to be typed when you press C-a :
    This changes the title of a window in a certain screen session:
    screen -X at 1 title blublublu

  23. tj says:

    kibitz is great for sharing a screen and work session. Tks to Sitaram Chamarty. Much simpler to implement than screen if your interest is primarily sharing sessions.

  24. torbiak says:

    Brian: If bash isn’t starting up how you expect it to when invoked by screen, it’s likely because bash reads different initialization files depending on how it’s started. Setting up a link from .bashrc to your favorite rc file [.bash_login, .bash_profile, .profile] might make it behave how you like.

    Maybe something like this: ln -s .bash_login .bashrc
    bash’s manpage has the details.

  25. Richard says:

    A way to broadcast commands to all windows is the following:
    ^a:at \# stuff “ls12″

    Thanks goes to Michael, (one of the screen devs) who provided this information to me.

  26. Richard says:

    The command above should read: double quote ls backslash zero twelve double quote. Somehow the parser removes the blackslash zero. One more try:
    ^a:at \# stuff “ls\\12″

  27. airtonix says:

    i use screent to run rtorrent on our homeserver.

    i also would like to provide a read only display of rtorrents screen output.

    i dont want press buttons to make a hardcopy, can i automate this on a timer?

    i want hardcopy to run every 5min.

  28. realthor says:

    Hi, I am very interested in the “chat to all tabs” function from secureCRT if it would be possible to do with screen it would be wonderfull but the command above doesn’t work. I am using screen under solaris I don’t know if it is any different but I have 50 sessions opened to 50 machines and sometimes I need to change a word in a file on all machines and it is very time consuming without this option.

    Can anyone help?

  29. Peter K says:

    Hi, all!

    If I understand it correctly what Jim C said: You can use screen to ‘recover’ sessions even if there are on a remote computer?

    Is the following scenario possible:
    1. ssh to a remote computer
    2. start screen (or should I start it on my local machine?)
    3. run a big task
    4. detach from this session
    5. ## shutdown the local computer ## e.g. go sleeping :-)
    6. restart the local computer
    7. re-attach to the remote computer to see the progress of the task

    Is this possbible? I tried it but I always get:

    XIO: fatal IO error 104 (Connection reset by peer) on X server “localhost:10.0
    after 0 requests (0 known processed) with 0 events remaining

    if I shut down the local machine. If not – all is fine.
    Any suggestions?

  30. Peter K says:

    Okay I got it: it was the specific big task which was the problem.

    PS: it is imortant to start screen on the remote machine, of course!

  31. Disclosed Information » Blog Archive » Shared GNUScreen Session says:

    [...] There’s a nice little howto that included this and some other tips (like, starting programs automatically and setting a status bar) at Redhat Magazine. Posted by bob Filed in tech [...]

  32. This Mind Intentionally Left Blank :: GNU Screen/vim love says:

    [...] So I did some research on how to optimize use of vim and screen together. The first thing I came up with was getting screen to display a nice bar at the bottom by adding this to my .screenrc: (Thanks, Red Hat Magazine!) [...]

  33. Screen also works on the Synology NAS | Edward de Leau says:

    [...] http://www.redhatmagazine.com/2007/09/27/a-guide-to-gnu-screen/ [...]

  34. altcrash.net » Blog Archive » Slicehost: Part 1 says:

    [...] If you’re not familiar with Screen, Red Hat Magazine has a nice little introduction [...]

  35. bobpeers -> blog » Diskstation Modding says:

    [...] There’s a great Red Hat Magazine article showing the basics plus how to set up a .screenrc config file to automatically start sessions or add a status bar to the bottom. [...]

  36. Intentando montar un VPS — yukei.net says:

    [...] Red Hat Magazine | A guide to GNU Screen [...]

  37. Use Linux Screen Command To Manage Multiple Shell Sessions says:

    [...] Screen is useful for running a script or other long process as yourself if you are worried about disconnecting from your SSH session or want to do some other things in the shell as the process runs. You will need screen installed to do this. This will really save you a lot of time with Linux servers. [...]

  38. Rob Nichols says:

    This is a great intro. I’ve used screen for many years. (Just stopped to count. I think it’s been a decade!) However, I’d never bothered with learning about the hardstatus line until this article. It’s a nice addition. Thanks!

    P.S. I think there are two mistakes in the example given. Again, this is my first foray in screen’s string escapes, so I might be way off. I think “%{=kw}” should have a space, as “%{= kw}”. Without this change on my system windows before the current are green instead of white. I also think there is an extra “%?” before the the closing “]” on the window list. This made no difference on my system. Here’s a version with these changes.

    hardstatus string ‘%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%= %{g}][%{B}%Y-%m-%d %{W}%c %{g}]‘

  39. John says:

    I’ve used Screen for more than a decade. For years now I’ve used it to keep open ssh sessions to various systems, doing things like tailing logs and such, and disconnecting then reconnecting when necessary. My latest session has been running upwards of 2 years, only ever bringing it down for critical patching. Sometimes I connect to the same session from multiple windows, displaying different screen “windows” for multiple views. I also use an always on statis as well.

    The few modifications I’ve made are to increase the MAXWIN param to allow for more windows, and change the command key to ^w so I don’t have to unlearn my emacs ^a habits.

  40. John Stoseel says:

    Wow dude, I think you might just be onto something here!

    Jess
    http://www.web-privacy.pro.tc

  41. Paul Prescod says:

    I used screen heavily in the mid-nineties. When I got back into remote Unix server stuff I was happy to see it was still around but a bit surprised that the state of the art had not evolved much.

    Yes, it’s true that screen allows you to rebuild your sessions despite a long gap in network connectivity…but why shouldn’t this be built into the network protocol rather than into a userland app? GMail will happily re-connect after quite a long gap…why not SSH?

    Why can’t I tell SSHD that I want to keep an SSH session alive indefinitely? Or detach it one place and reattach it somewhere else? I think it is more correct to do it at that level because:

    a) SSH is more general than just interactive usages

    b) Screen interferes with command keys, beeps, client-sie scrollback and other stuff.

    Or another way to think about it is that perhaps screen should be the default interactive shell and client-side terminals and server-side apps should take seriously the requirement to work seamlessly with screen.

    Currently it is invasive and gives you some good features at the same time that it breaks other stuff that were not written with it in mind (like apps that use Ctrl-A and nice terminal scrollback).

    According to the docs for my iphone terminal emulator:

    “Please note that due to incompatibilities between GNU screen and the VT100 standard used by TouchTerm, there may be some terminal emulation problems when using screen-based applications such as emacs and vi. We also recommend that you set the ‘Allow Scrollback’ Option to Off when using any screen-based application with Persistent Connections enabled, as this tends to reduce errors caused by the emulation incompatibility. However, if you make frequent use of such programs, we recommend that you leave this Option disabled.”

    Unfortunately, screen is not “standard” enough that all client and server apps have figued out how to work totally seamlessly with it and it has not become standard enough in 20 years.

    It’s a wonderful thing: but a hack around deeper flaws in the whole terminal emulation mechanism.

  42. Rhys Ulerich says:

    There’s a fairly easy way to have GNU screen started every time you open a gnome-terminal. Equivalently, this lets multiple gnome-terminals share a single screen session. Very handy: http://agentzlerich.blogspot.com/2008/07/using-gnu-screen-with-gnome-terminals.html

  43. links for 2009-01-08 « Donghai Ma says:

    [...] Red Hat Magazine | A guide to GNU Screen (tags: reference tips linux tools sysadmin screen console terminal) [...]

  44. links for 2009-01-08 « My Weblog says:

    [...] Red Hat Magazine | A guide to GNU Screen (tags: tutorial linux) [...]

  45. gfrast / Daily hand picked web links - mixed with a shot of reality. says:

    [...] Jan. 9th http://www.redhatmagazine.com11:05 h Screen HOWTO 0 [...]

  46. Marc Andre Tanner says:

    Those of you who prefere a lightweight and hackable solution might find my dvtm project in conjunction with dtach interesting. A new version will be published soon.

    http://www.brain-dump.org/projects/dvtm/

    /end of advertising campaign

  47. Anton Olsen.com » Blog Archive » Bookmarks for January 9th says:

    [...] Red Hat Magazine | A guide to GNU ScreenInstead of opening up several terminal instances on your desktop or using those ugly GNOME/KDE-based tabs, Screen can do it better and simpler. [...]

  48. John Pye says:

    One good use of Screen is when performing remote updates of systems using apt-get or yum. You can start the update going, then disconnect, then come back later and check that it finished OK. If your remote connection goes down, it doesn’t mess everything up. Also, using the screen ‘logging’ function, you can keep a full history of the update, and check it for error messages that you might have missed.

  49. Ravi says:

    A very nice introduction to the screen command. Loved reading it.

  50. A Drop In The Stream › links for 2009-02-03 says:

    [...] Red Hat Magazine | A guide to GNU Screen (tags: linux howto sysadmin shell terminal screen) This was written by doug. Posted on Tuesday, February 3, 2009, at 9:05 pm. Filed under del.icio.us Links. Bookmark the permalink. Follow comments here with the RSS feed. Post a comment or leave a trackback. [...]

  51. Doug Bell says:

    In screens 1-16 I can, from commandline, ‘export box=STB_n’ where n is the screen number essentially.
    Is there a way to write some bash script to run in screen 0 to do this programatically?

    The usage is that later I can:
    C-a : at \# stuff “echo box is 44box 12″ to get output like
    box is STB_7
    in screen 7, etc.

    I’d like to eventually be able to ( with a script ) echo commands out to all screens simultaneously but have the commands interpreted differently based on local environment variables. ( like ssh $box )

  52. jeffatrackaid says:

    I’ve been using screen for a long time and think it is a highly underutilized program.

    I use it for training purposes sometimes using the dual attachment mode. screen -X

    I also can have staff log actions for review later.

  53. Kris’s Technical Knowledge Base » Blog Archive » A guide to GNU Screen says:

    [...] http://magazine.redhat.com/2007/09/27/a-guide-to-gnu-screen/ [...]

  54. Linux Screen « Datacluster’s Weblog says:

    [...] leave a comment » A Good tutorial on screen : http://magazine.redhat.com/2007/09/27/a-guide-to-gnu-screen/ [...]