Manage Multiple Terminals with Screen

LinuxLinuxBeginner
Practice Now

Introduction

The screen command is extremely useful for running multiple scripts simultaneously in the background. This allows you to start long-running tasks without keeping a terminal open for each one. Below, we'll go through how to use screen to run scripts in the background and manage these sessions.

htop

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/PackagesandSoftwaresGroup(["`Packages and Softwares`"]) linux/PackagesandSoftwaresGroup -.-> linux/software("`Linux Software`") subgraph Lab Skills linux/software -.-> lab-271827{{"`Manage Multiple Terminals with Screen`"}} end

Running Scripts in Background

You have three scripts that perform different tasks in ~/project.

Open the terminal ( ① or ② in the figure ) in the environment and enter the following command:

ls ~/project
htop

If you want to run these 3 scripts at the same time, you may do like this:

htop

Now, we'll use screen to run these scripts simultaneously in detached sessions.

To run these scripts in the background using screen, we'll use the -dmS option:

  • -d starts a session and immediately detaches from it.
  • -m forces screen to create a new session.
  • -S allows us to name the session for easy reference.

Starting the Scripts

Open one terminal and navigate to the directory containing your scripts. Then, start each script in a separate screen session using the following commands:

screen -dmS task1 ./script1.sh
screen -dmS task2 ./script2.sh
screen -dmS task3 ./script3.sh

Managing Sessions

After starting the scripts, you can manage these screen sessions with various commands.

List all sessions

screen -ls
htop

This command will show all your running screen sessions.

Reattach to a sessio

screen -r session_name

If you want to check the output or interact with a specific script, use this command to reattach to its session. Replace session_name with the name you assigned when starting the script (e.g., task1, task2, or task3).

Detach from a session

Once you're done checking a session, you can detach from it and let it continue running in the background by pressing Ctrl-a followed by d.

Terminate a session

To terminate a session, reattach to it using screen -r session_name and then type exit or press Ctrl-d.

Summary

Using screen to manage multiple background tasks can significantly streamline your workflow, especially when dealing with long-running or background processes. By running scripts in detached screen sessions, you maintain a clean workspace and ensure that your processes continue uninterrupted, even if you disconnect from the server or close your terminal.

Experiment with screen to discover how it can best fit into your workflow and enhance your productivity!

Other Linux Tutorials you may like