jobs

2025-01-17

Understanding Background Processes

Before refreshing our memory on background processes, let’s quickly review them. In Linux, you can run commands in the background by appending an ampersand (&) to the command. This allows you to continue using your shell while the command executes asynchronously.

sleep 10 &  # Runs 'sleep 10' in the background

This command will sleep for 10 seconds without blocking your terminal. Now, how do you manage this background process? That’s where jobs comes in.

Listing Background Jobs

The simplest use of jobs is to list all currently running background jobs. Simply type jobs and press Enter.

sleep 10 &
sleep 20 &
jobs

This will output something similar to:

[1]   Running                 sleep 10 &
[2]   Running                 sleep 20 &

This shows the job number ([1], [2]), the job status (Running), and the command being executed.

Controlling Background Jobs

jobs offers more than just listing; it provides tools to control these background processes.

fg %1  # Brings job number 1 to the foreground
fg %sleep # Brings the first background job containing "sleep" to the foreground
kill %2  # Sends SIGTERM to job number 2

To forcefully kill a job, use kill -9 %job_number which sends the SIGKILL signal. This signal cannot be caught or ignored. Use with caution!

sleep 10 &
sleep 20 &
jobs -l

This will output something like:

[1]+  Running         12345  sleep 10 &
[2]-  Running         12346  sleep 20 &

Where 12345 and 12346 represent the process IDs. This is useful if you need to interact with the job using other command-line tools that require PIDs.

sleep 10 &
wait %1 # wait for job 1 to complete
echo "Job 1 is complete"

Working with Multiple Shells

It’s important to remember that jobs only manages background processes within the current shell. If you open a new terminal or a new shell instance, the background processes from the previous shell are not managed by jobs in the new shell.

This detailed exploration of jobs provides a detailed understanding of how to effectively manage background processes in your Linux shell. By mastering this command, you can improve your shell productivity and workflow.