Linux Commands: jobs, bg, and fg
In this quick tutorial, I want to look at the
jobs command and a few of the ways that we can manipulate the jobs running on our systems. In short, controlling jobs lets you suspend and resume processes started in your Linux shell.
jobs command will list all jobs on the system; active, stopped, or otherwise. Before I explore the command and output, I'll create a job on my system.
I will use the
sleep job as it won't change my system in any meaningful way.
[tcarrigan@rhel ~]$ sleep 500 ^Z + Stopped sleep 500
First, I issued the
sleep command, and then I received the Job number . I then immediately stopped the job by using Ctl+Z. Next, I run the
jobs command to view the newly created job:
[tcarrigan@rhel ~]$ jobs + Stopped sleep 500
You can see that I have a single stopped job identified by the job number .
Other options to know for this command include:
- -l - list PIDs in addition to default info
- -n - list only processes that have changed since the last notification
- -p - list PIDs only
- -r - show only running jobs
- -s - show only stopped jobs
Next, I'll resume the
sleep job in the background. To do this, I use the
bg command. Now, the
bg command has a pretty simple syntax, as seen here:
Where JOB_SPEC can be any of the following:
- %n - where n is the job number
- %abc - refers to a job started by a command beginning with abc
- %?abc - refers to a job started by a command containing abc
- %- - specifies the previous job
fg operate on the current job if no JOB_SPEC is provided.
I can move this job to the background by using the job number .
[tcarrigan@rhel ~]$ bg %1 + sleep 500 &
You can see now that I have a single running job in the background.
[tcarrigan@rhel ~]$ jobs + Running sleep 500 &
Now, let's look at how to move a background job into the foreground. To do this, I use the
fg command. The command syntax is the same for the foreground command as with the background command.
Refer to the above bullets for details on JOB_SPEC.
I have started a new
sleep in the background:
[tcarrigan@rhel ~]$ sleep 500 &  5599
Now, I'll move it to the foreground by using the following command:
[tcarrigan@rhel ~]$ fg %2 sleep 500
fg command has now brought my system back into a sleep state.
While I realize that the jobs presented here were trivial, these concepts can be applied to more than just the
sleep command. If you run into a situation that requires it, you now have the knowledge to move running or stopped jobs from the foreground to background and back again.
[ Free online course: Red Hat Enterprise Linux technical overview. ]