Screen

From Gentoo Linux Wiki

Jump to: navigation, search
Fix me: There a still missing informations (compared to the article "TIP Using screen" from the old wiki). This page's discussion section has a link where an archived copy can be retrieved.

Screen is a moderately complex program that emulates a terminal. The feature it is best known for is the ability to disconnect and reconnect to screen sessions, which very gracefully survive logoffs. Screen has many more useful features, which are beyond the scope of this guide. Please refer to the GNU Screen Project Page for more information.

If you do not like unnecessary windows open, or want to get the maximum out of your terminal session, screen will soon be in your .bash_history numerous times.

Contents

[edit] Getting started with Screen

First you have to install the program (if it isn't already installed). This is as simple as
emerge -av app-misc/screen
To start using Screen open a terminal and type
screen

Depending on the setup of Screen you may be greeted by a startup message, but Gentoo has this usually disabled in /etc/screenrc with the line startup_message off. More about those settings later.

Initial startup message
Note: To initiate a command to Screen it uses a special keystroke, by default control-a (abbreviated C-a from now on).

The first sign of Screen successfully running can be discovered by typing C-a " which shows the list of terminals. At the moment there is only one. The Esc key exits that window. Alternatively, use C-a w to list them briefly in the window's title bar.

Window list with one entry

To create a new terminal just type C-a c. The windowlist (C-a ") lists now two terminals, the old and the new one. Naming the open terminals helps keeping an overview. Therefore C-a A allows you to give your new terminal a name.

With C-a n for next or C-a p for previous you can cycle through your open windows.

[edit] Detach and Reattach

One of the most useful features of GNU Screen is: If we close the parent terminal Screen continues running! It simply "detaches" and can be accessed again — without any effect on the tasks running. Which makes it ideal for working on remote machines.

To detach your open Screen session just type C-a d or simply close it by closing the terminal window.

We are now dropped back into the shell that we started with in the beginning. At first we want to check if there is really a Screen-session running. These are listed by
screen -ls
To access this one instance we re-attach with
screen -R
Voilà, here we go again!

This already explains the basic usage of Screen, and gives us a method to leave compiles running on a remote or local system without the need to keep a terminal open all the time.

[edit] Orphaned screen sessions

A remote Screen session is sometimes not properly detached when e.g. the local xterm was killed or the net connection died. The session will show as attached when listing them with screen -ls.

To attach to this session you can either use its session name or tell Screen to detach it first, which is the easiest way if there is only one session existing.

# detach and reattach to a running screen screen -DR

To attach a specific session out of a list returned by screen -ls, like -r [pid.tty.host], where [pid.tty.host] is e.g. 13539.pts-0.hostname, use screen -r 13539.pts-0.hostname although you only have to type the first unique number, in this example typing screen -r 1 would attach to the 13539.pts-0.hostname screen session.

[edit] Naming screen sessions

You can make reattaching to a running screen session easier by giving the session a unique name when you start it.

screen -S foo

This will create a new screen session named foo. If you can create another screen session named bar. You can then select to either session by using the given name.

screen -R bar screen -R foo

[edit] Resizing a window to fit your terminal

Sometimes you may connect to a screen from a terminal with different geometry from when the session was started. To resize a specific window you can use C-a F to "fit" the window to the current terminal.

If you know before you attach to a screen that you want to resize all windows to fit you current terminal you can use the -A option to .

screen -A

[edit] Quitting screen

One way to close a Screen session is to exit all terminal sessions you are running inside, one after the other. After the last exit inside Screen you will get [screen is terminating] as a confirmation that your Screen session has ended.

However, a simpler and faster way to do the same thing is to use Screen's quit command.

C-a :quit

This will kill all programs running inside the current Screen session and exit the session. If you use this command frequently, it may be useful to create a keybinding in your configuration file:

File: ~/.screenrc

# bind F10 to Screen's quit command
bindkey -k k; quit

See the "INPUT TRANSLATION" section of the Screen manual for details on how to bind function keys (e.g, F1, F2, etc.).

[edit] Regions

screen with two regions: the newsreader slrn and the IRC client Irssi

Similar to vim we can use a single terminal window for more than one visible task.

Screen can horizontally split into regions, each holding a different terminal. To open a new region one types C-a S (capital s, please!). To enter that newly created region we have to tab into it: C-a <Tab> Still nothing can be seen, but we can now cycle through our open terminals with C-a n or C-a p.
To close a region type C-a X. A region with focus can be resized with C-a + or C-a - By default this changes the height by 3 lines. Alternatively, you can specify the height to an absolute number by going into Screen's command mode. C-a :resize 20 makes the currently focused region 20 lines high.

[edit] Scrolling back in screen

To enter the scrollback mode press C-a [. When you do this, a notice briefly appears in the terminal's status-bar, which says "Copy mode...". Now, you can scroll up and down in the current terminal using the PageUp/PageDown keys or the C-u and C-d commands. Although quite useful by itself, scrollback mode is even more powerful when combined with copy and paste.

If you use scrollback feature a lot and you are using URxvt, then you might want to set:

File: ~/.Xdefaults
URxvt*secondaryScroll: true

This enables you to use Shift-PageUp/Shift-PageDown to move back and forth in scroll buffer. Another frequent cause of using scrollback buffer is, when programs like Vim exit they leave their content on the window. To get rid of this behavior use:

File: ~/.screenrc
altscreen on

[edit] Selecting text, copying, pasting

Copying works by selecting a start position and an end position for text to be copied. These are marked with the cursor's current position by pressing Space. Between two strokes the buffer can be navigated with h,j,k,l, they work just as in the editor vim. On most machines you can also use the arrow keys as well if you are not familiar with vim movement commands. And for the fans of emacs this default behavior can be changed in .screenrc. Consult the man page for the wealth of other movement commands available.

The content of the buffer can then be pasted back into any other Screen window of the current session by typing C-a ].

[edit] Advanced copying

One can even access the file system to copy files into Screen, or concatenate selections in a Screen window into a file on the machine where Screen is running on. To copy a funny signature from a Usenet posting set Screen into copy mode with C-a [, select the text between two space keystrokes and then set a buffer file in the current directory with C-a :bufferfile notes.txt. This file is written into (and overwritten if existing!) by C-a >.

Note that C-a : sets Screen in the command mode and you actually type in Screen's status-bar. If no buffer file is given, Screen uses a default /tmp/screen-exchange, because this feature is primarily meant for exchanging data between Screen users on the same system.

[edit] Command mode

Typing C-a : puts Screen into command mode and the status line at the bottom changes. Screen now accepts direct commands.


[edit] Accessing open terminals

In addition to cycling through open terminals using C-a n and C-a p, you can directly access terminals 0-9 with C-a # where # is 0-9. (I.e. C-a 1 will switch to terminal 1; C-a 8 will switch to terminal 8.).

If you spend a lot of time on the command line and have more than ten windows open, you can get better access to higher terminals than C-a " by adding this to your ~/.screenrc

File: ~/.screenrc
bind -c selectHighs 0 select 10 #these three commands are 
bind -c selectHighs 1 select 11 #added to the command-class
bind -c selectHighs 2 select 12 #selectHighs

bind - command -c selectHighs   #bind the hyphen to 
                                #command-class selectHighs 

Issue the command C-a :source .screenrc to re-source your settings.

Now C-a -0 opens the 10th terminal under Screen's control (if it exists).

[edit] Monitoring a Window for Silence or Activity

screen in regions mode with tab-bar

You may have multiple windows open with various task in each and would like to monitor different windows for activity or silence, like you have an IRC client in one window, and emerge running in another, and are working on code in a third. You might want to know when emerge is done or if someone speaks in IRC.

The command C-a _ turns on monitoring mode for 15 seconds of silence in the current window, which triggers a notification in your terminal's status area. Repeat the command to switch off the monitoring.

The command sequence C-a M turns on monitoring for all activity in the current window. Repeat the command to turn it off.

[edit] Control a Screen within a Screen

Sometimes it can happen that you accidentally start screen from within screen or attach to a screen from within a screen. When you try to detach from the inner screen, you actually detach from the outer screen. The problem is that your first screen will catch the C-a d. To control a screen within a different screen you have to first hit C-a and then do what you want to do with the other screen, without the C-.

Command Effect
screen
Start screen session 1
screen -r
Attach screen session 2 within screen session 1
C-a Tells session 1 to wait for a command (command pending)
a Tells session 1 to send the escape sequence, which tells session 2 to listen
d Tells the second session to detach

Using this method, one can control any number of nested screen sessions within other screen sessions, you just have to keep adding an additional a meta-command character for every nested screen instance. This can becomes a bear to keep all of them straight in your head. To overcome this, some people will set the escape sequence differently depending on the nested level of the screen session.


[edit] Configuring Screen sessions with .screenrc

File: ~/.screenrc
vbell off        # turns off the flashing visual bell

# Open several named screens at startup and run different commands in each
screen -t E-Mail     2   mutt -y
screen -t irssi      3   irssi
screen -t mp3blaster 4   stuff "mp3blaster\015"
screen -t news       5   slrn  -h  news.individual.net -f /home/cprior/.jnewsrc
screen -t rss        6   raggle
screen -t root       1   su -

The window opened last is the one that is left active after screen starts up. See -p in the man pages for to change the preselected window. When the command used to open the window ends, that window closes. The above syntax for mp3blaster runs the command, but leaves the window open when the program terminates.

You can specify any file to be used in place of ~/.screenrc by using the -c option.

# use /dev/null for configuration screen -c /dev/null


[edit] Changing the escape sequence

Sometimes you may want to change the default escape sequence C-a to something different (E.g. nesting screen sessions).

File: ~/.screenrc
escape ``

If you want to have the backtick toggle between the two most recent windows as C-a C-a would, you should instead have something similar to the following in your ~/.screenrc:

File: ~/.screenrc
escape `e

This will bind the backtick character to ` e and allow ` ` to toggle windows. Note that this will clobber whatever ` e was previously bound to. 'e' is chosen here as it is not used by default.

Please note that using the backtick can cause problems with mouse-scrolling, as the wheel's escape code can have a backtick in it.

Some programmers may find it quite inconvenient to use the backtick, so feel free to experiment with other characters or simply use the default setting.

Emacs uses C-a for beginning-of-line. It is also the command key for Screen, which causes the problem of muscle memory impedence matching. This can be avoided with the following, which binds the command key of screen to C-o.

File: ~/.screenrc
escape ^Oo

C-t is also a popular choice, although this will conflict with the transpose function. Also C-t is the default for the Ratpoison Window Manager. (which is very Screen-like and works well with Emacs and Screen)


[edit] Tab-bar

A really nice thing is make Screen show a "tab-bar" with your open windows.

You can add this functionality by adding the following lines to your ~/.screenrc file.

File: ~/.screenrc
#change the hardstatus settings to give an window list at the bottom of the
#screen, with the time and date and with the current window highlighted
hardstatus alwayslastline 
hardstatus string '%{= mK}%-Lw%{= KW}%50>%n%f* %t%{= mK}%+Lw%< %{= kG}%-=%D %d %M %Y %c:%s%{-}'

Another one you could try

File: ~/.screenrc
hardstatus string '%{= kG}%-Lw%{= kW}%50> %n%f* %t%{= kG}%+Lw%< %{= kG}%-=%c:%s%{-}'

A very nice one is this one with hostname, centered tabs and redmarked active windows:

File: ~/.screenrc
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %d/%m %{W}%c %{g}]'

[edit] Multi-user mode

Useful for collaborative install sessions is the multiuser mode of Screen. Just execute
screen -x
to attach to a Screen multiple times.
Note: Gentoo disabled this by default on older ebuilds of Screen because it required Screen to be setuid root. If you have trouble try updating your copy of Screen.

[edit] Quick walk-through

Command Effect
screen
Login and start a Screen session right away
C-a " Show list of terminals managed by Screen; Here: only one
Esc Close the list window
C-a c Create a new terminal window
C-a " The list of terminals now shows two entries
Esc Close the list window
ls
show the directory contents in this window
C-a p return to the previous, first window
ping forums.gentoo.org
Do something in this window, too
C-a c Create another window
C-a S Split the term horizontally into two regions
C-a X Kill the current region
C-a Tab Focus the newly created region
C-a - Resize this region and make it 3 lines smaller
C-a 1 Show the first window in this region
C-a Tab Move the focus back to the upper region
C-a d Detach the Screen session
open a xterm
screen -DR
login again and make Screen re-attach (R) to the first session found, after detaching (D) the session first, if necessary (which it wasn't)

[edit] Troubleshooting

[edit] Problems with screens being "frozen"?

It is easy to confuse C-a S, which a uses a capital 'S' with C-a s, which uses a lower case 's'. The upper case command causes screen to be horizontally split (that is, with one region on top of the other), while the lower case command causes the parent terminal to freeze (why in the world does this command exist?!?!). To unfreeze the parent terminal, use the C-a q command.

To remove this command, use the command sequence: bind s. This command can be entered at the colon (':') prompt or in the screen startup file.

What happens is that Screen sends a Ctrl-z (xoff) to the screen, which freezes all output. The screen command C-a s is bound to the xoff command. You achieve the same effect in most terminals running bash by typing Ctrl-s. (Type Ctrl-q to undo this effect)

You might have noticed that you can still navigate and use the other windows, and even create new ones after an accidental C-a s. To continue, use the C-a q (which is the xon command). For a proper lock of the session simply type C-a x and only your password gives you access again.

You may also have a problem with Ctrl-z which sends a suspend to the terminal. Type once again to resume and/or turn off altogether with the stty command.

It is also to be noted that when dealing with uppercase commands, you can't type the whole command (i.e C-a S) in a sequence. You must first C-a then Shift-s

[edit] See Also

Personal tools
In other languages