Using jobs Command
Introduction
The jobs command in Unix-like operating systems is used to display the status of jobs managed by the current shell session. Jobs are processes that are started by the shell. Understanding how to use the jobs command effectively can help you manage background and foreground processes efficiently.
Basic Usage
To see the list of current jobs, simply run the jobs command without any arguments:
jobs
[2]- Stopped nano
In this example, the output shows two jobs. The first job is a background job running the sleep 100 command, and the second job is a stopped nano editor.
Job States
Jobs can be in different states:
- Running: The job is currently executing.
- Stopped: The job has been paused by a signal.
- Terminated: The job has completed execution.
Controlling Jobs
Bringing a Job to the Foreground
To bring a background job to the foreground, use the fg command followed by the job number:
fg %1
This command brings job number 1 to the foreground.
Sending a Job to the Background
To send a foreground job to the background, use the bg command followed by the job number:
bg %2
This command resumes job number 2 in the background.
Managing Job Control
Stopping a Job
To stop a running job, use the Ctrl+Z keyboard shortcut. This will suspend the job and return you to the shell prompt. For example:
sleep 100
(Press Ctrl+Z)
Resuming a Stopped Job
To resume a stopped job in the foreground, use the fg command:
fg %1
To resume a stopped job in the background, use the bg command:
bg %1
Practical Examples
Example 1: Running Multiple Background Jobs
Here’s how you can start multiple background jobs and list them using the jobs command:
sleep 100 &
sleep 200 &
jobs
[2]+ Running sleep 200 &
Example 2: Managing Job States
Start a job, stop it, and then resume it:
nano
(Press Ctrl+Z)
bg %1
jobs
Conclusion
The jobs command is a powerful tool for managing processes in a Unix-like operating system. By understanding how to list, stop, and resume jobs, you can effectively control the execution of multiple processes within your shell session. Use this knowledge to manage your command-line tasks more efficiently.