Creating and Running Background Tasks
In this step, you will learn how to create a script that simulates a long-running task and run it in the background.
Understanding Foreground vs Background Processes
In a Linux terminal, processes can run in either the foreground or background:
- Foreground process: When a command runs in the foreground, it occupies your terminal until it completes. You cannot run other commands until it finishes.
- Background process: When a command runs in the background, it executes "behind the scenes" while your terminal remains free for other tasks.
Let's start by navigating to the project directory:
cd ~/project
Now, let's create a simple script that simulates a long-running task. We'll use this to demonstrate background and foreground operations:
nano long_running_task.sh
In the nano editor, enter the following code:
#!/bin/bash
echo "Starting a long task..."
sleep 60 ## This will pause for 60 seconds
echo "Task completed."
To save the file, press Ctrl+O
followed by Enter
, and then Ctrl+X
to exit nano.
Next, make the script executable with the following command:
chmod +x long_running_task.sh
Let's run this script in the background by adding an ampersand (&
) at the end of the command:
./long_running_task.sh &
You should see output similar to this:
[1] 1234
Starting a long task...
The number in square brackets [1]
is the job number, and the number after it (in this example, 1234
) is the process ID. Your terminal is now free for you to enter other commands while the script continues running in the background.