How to Install and Use Screen to Manage Terminal Sessions on Linux

Posted on

How to Install and Use Screen to Manage Terminal Sessions on Linux

Use Screen to Manage Terminal Sessions on Ubuntu Debian CentOS RedHat

Screen is a powerful terminal multiplexer. It allows you to manage multiple terminal sessions within a single window or SSH connection. This is particularly beneficial on remote Linux servers, like Ubuntu cloud instances, where you need to run long-lasting processes that should continue even after you disconnect. You can detach from these sessions and reattach later without interrupting the processes. Let’s explore how to install and effectively use Screen on an Ubuntu cloud server.

Installing Screen

Most Ubuntu distributions come with Screen pre-installed. To verify if it’s already on your system, run:

$ screen -v

If Screen is installed, you’ll see output similar to this:

Screen version 4.08.00 (GNU) 5-Oct-20

If it’s not present, you can easily install it using the following commands:

$ sudo apt update
$ sudo apt install screen

Starting a Screen Session

To initiate a new Screen session, simply type:

$ screen

This will present you with a new, blank terminal screen. Any commands you execute within this screen are isolated to that session.

You can also start a named Screen session by providing a session name:

$ screen -S session1

To view a list of all active Screen sessions, use:

$ screen -ls

Detaching and Reattaching to a Screen

One of the key benefits of Screen is the ability to detach from a session while it continues running in the background. To detach, press Ctrl+A, followed by D.

You’ll be returned to your regular terminal prompt, and the Screen session will persist in the background.

To reattach to a detached Screen session, use the following command, replacing "session1" with the actual name of your session:

$ screen -r session1

If you omit the session name, Screen will attempt to reattach to the most recently detached session.

Handy Screen Commands

Here are some useful commands you can use within a Screen session:

  • Ctrl+A C: Create a new window.
  • Ctrl+A N: Move to the next window.
  • Ctrl+A P: Move to the previous window.
  • Ctrl+A 0-9: Switch to window number 0-9.
  • Ctrl+A K: Kill the current window.
  • Ctrl+A A: Rename the current window.
  • Ctrl+A D: Detach from the Screen session.
  • Ctrl+A ?: Display a help message with all available commands.

Configuring Screen

You can customize Screen’s behavior by editing the ~/.screenrc file. Some useful settings include:

# Enable mouse scrolling
termcapinfo xterm* ti@:te@
# Change escape key from Ctrl+A to Ctrl+B
escape ^Bb
# Change screen log file location
logfile ~/.screens/screenlog.%n

Refer to the Screen manual page (man screen) for a complete list of configuration options.

By default, Screen doesn’t allow scrolling through previous output like a normal terminal.

To enable scrolling, you need to enter copy mode by pressing Ctrl+A followed by [. Use the arrow keys, Page Up, and Page Down to navigate the output. Press Esc to exit copy mode.

Alternatively, you can enable a scrollback buffer in your ~/.screenrc file:

defscrollback 30000

This will store the last 30,000 lines of output, allowing you to scroll through them using the copy mode.

Screen with SSH

Screen is particularly useful when working with SSH connections.

Start a Screen session on the remote server, then detach it as usual with Ctrl+A D.

Log out of your SSH session. When you log back in later, you can reattach to your previous session using:

$ screen -r

This allows you to continue running processes on the remote server even after you’ve disconnected and reconnected.

Tmux vs Screen

Screen shares similarities with tmux, another popular terminal multiplexer. Key differences include:

  • Features: Tmux generally offers more features than Screen, such as a more customizable status line, better window management, and a client-server architecture.
  • Configuration: Tmux configuration is often considered more flexible and powerful than Screen’s.
  • Usability: Some users find tmux’s command syntax and default keybindings more intuitive.

In summary, tmux might be preferable for users seeking advanced features and greater customization, while Screen remains a solid and lightweight choice for basic terminal multiplexing.

Screen Man Page

The Screen man page is an invaluable resource for understanding all the command-line options and configuration settings.

Access it by running:

$ man screen

Here are some highlights from the man page:

Command Line Options

Common command-line options when launching screen:

  • -d -m: Starts Screen in detached mode.
  • -S <session_name>: Specifies a name for the Screen session.
  • -r <session_name>: Attaches to a detached Screen session.

Configuration File

The ~/.screenrc file controls Screen’s behavior:

# Set default window name
screen -t shell
# Set screen logging file
log on
logfile ~/screenlog.0
# Set scrollback buffer size
defscrollback 30000

Bound Commands

Binding commands to keystrokes:

# Bind Ctrl+A C to create a new window
bind C create
# Bind Ctrl+A n to switch to next window
bind n next

Copy/Paste

Screen offers copy/paste support:

# Enter copy mode
Ctrl+A [
# Begin selecting text with arrow keys
# Copy selected text
Ctrl+A ]
# Paste copied text
Ctrl+A ]

Windows

Managing windows:

# Create new window
$ screen -t test
# Switch between windows
Ctrl+A n
# Kill current window
$ quit

This covers some of the most popular Screen usage direct from the man page. Refer to man screen for more details.

Conclusion

How to install and use Screen to manage terminal sessions on Linux is a powerful guide that explains Screen, a handy utility for running processes on remote servers like Ubuntu cloud VMs where you want to detach and reattach to sessions.

Key tasks covered:

  • Installing Screen
  • Starting, detaching, and reattaching to Screen sessions
  • Configuring Screen for enhanced usability
  • Using Screen with SSH

Screen remains relevant today alongside newer tools like tmux and is worth learning if you manage remote Linux servers. It provides an easy way to keep sessions running even when you get disconnected from the server. How to install and use Screen to manage terminal sessions on Linux is an important skill for Linux server administration.

Alternative Solutions

While Screen is a reliable tool, alternative methods exist for managing long-running processes on Linux servers. Here are two such alternatives:

1. Using nohup and Backgrounding Processes

The nohup command allows a process to continue running even after you log out of the terminal. Combined with backgrounding a process using the & operator, it provides a simple way to keep processes running.

Explanation:

  • nohup: Prevents the process from receiving the SIGHUP signal (hang up), which is typically sent when a terminal session ends.
  • &: Runs the process in the background, freeing up your terminal.
  • Output Redirection: It is essential to redirect both standard output and standard error.

Code Example:

Let’s say you want to run a long-running script called my_script.sh. Instead of running it directly, you can use the following command:

nohup ./my_script.sh > output.log 2>&1 &
  • nohup ./my_script.sh: Executes the script using nohup.
  • > output.log: Redirects standard output to a file named output.log.
  • 2>&1: Redirects standard error (file descriptor 2) to the same location as standard output (file descriptor 1). This ensures that any errors are also logged to output.log.
  • &: Runs the entire command in the background.

To check the status of the background process, you can use the jobs command or ps aux | grep my_script.sh. To bring the process to the foreground, use the fg command followed by the job ID (if you used jobs).

Advantages:

  • Simple and readily available on most Linux systems.
  • No need to install additional software.

Disadvantages:

  • Limited control over the process once it’s running in the background.
  • No session management capabilities like Screen or tmux.
  • Can be difficult to reattach to a running process.

2. Using Systemd Services

Systemd is a system and service manager for Linux operating systems. It provides a more robust and sophisticated way to manage long-running processes as services.

Explanation:

  • Systemd services are defined in unit files (typically located in /etc/systemd/system/).
  • These unit files specify how the service should be started, stopped, restarted, and managed.
  • Systemd automatically handles process monitoring, logging, and restarting in case of failures.

Code Example:

  1. Create a Systemd Unit File:

    Create a file named my_script.service in /etc/systemd/system/:

    sudo nano /etc/systemd/system/my_script.service

    Add the following content, modifying the paths as necessary:

    [Unit]
    Description=My Long Running Script
    After=network.target
    
    [Service]
    User=your_username
    WorkingDirectory=/home/your_username/scripts
    ExecStart=/home/your_username/scripts/my_script.sh
    Restart=on-failure
    RestartSec=10
    
    [Install]
    WantedBy=multi-user.target
    • Description: A brief description of the service.
    • After=network.target: Specifies that the service should start after the network is up.
    • User: The user account under which the service should run. Important: Replace your_username with your actual username.
    • WorkingDirectory: The directory where the script is located.
    • ExecStart: The command to execute to start the service.
    • Restart=on-failure: Specifies that the service should be restarted automatically if it fails.
    • RestartSec=10: Specifies the delay (in seconds) before attempting to restart the service.
    • WantedBy=multi-user.target: Specifies that the service should be started when the system enters the multi-user runlevel.
  2. Enable and Start the Service:

    sudo systemctl enable my_script.service
    sudo systemctl start my_script.service
    • systemctl enable: Enables the service to start automatically at boot time.
    • systemctl start: Starts the service immediately.
  3. Check the Service Status:

    sudo systemctl status my_script.service

    This will display information about the service, including its current status, logs, and any errors.

  4. Stop and Disable the Service:

    sudo systemctl stop my_script.service
    sudo systemctl disable my_script.service

Advantages:

  • Robust and reliable service management.
  • Automatic restart on failure.
  • Centralized logging and monitoring.
  • Integration with the system’s boot process.

Disadvantages:

  • More complex configuration compared to nohup or Screen.
  • Requires understanding of systemd concepts.

In conclusion, while nohup provides a quick and simple solution, and Screen allows session management, Systemd offers a more structured and reliable approach for managing long-running processes as services on Linux systems. The choice depends on the complexity of your needs and the level of control you require. How to install and use Screen to manage terminal sessions on Linux provides a critical skillset, but understanding these alternatives can significantly improve your overall Linux system administration capabilities.