How to Use Screen Command for Long-Running Background Tasks

Introduction to the Screen Command


The screen command in Unix-like systems allows you to run long tasks in the background without being tied to an active terminal session. This setup is particularly useful for long-running scripts or tasks on remote servers, where keeping an active connection isn’t always feasible. Here’s how to use it.

Basic Usage

    Start a New Screen Session.Replace session_name with a name for your session to make it easier to identify.
screen -S session_name
    Run Your Command.Run the long-running task as you normally would. For example:
./long_task.sh
    Detach from the Screen Session.Press Ctrl + A, then D to detach from the session and leave the task running in the background.
    List Screen Sessions.To see a list of all active screen sessions, use:
screen -ls
    Reattach to a Screen Session.To reattach to a session, use (if you didn’t name your session, you can use the session ID listed from screen -ls):
screen -r session_name
    Terminate a Screen Session.To terminate a session, reattach to it and then exit the shell by typing exit or pressing Ctrl + D.

Additional Tips

Running Commands Directly in Background

You can start a command directly in a new screen session without manually entering it:
screen -S session_name -d -m your_command

Scrolling in Screen

If you need to scroll through the output, press Ctrl + A then [ to enter scroll-back mode. Use arrow keys to navigate, and press q to exit scroll-back mode.

Copying Text

Press Ctrl + A then [ to enter copy mode. Use the arrow keys to move the cursor to the beginning of the text you want to copy, press Enter, move to the end of the text, and press Enter again.