In Linux and Unix systems, a job is defined as a task that has started running and not yet completed. Each task is basically programs in execution which is a process.
Each job is assigned with a unique id called job number (Job ID). We can run the jobs in the background without any intervention from the user and also be run in the foreground as current jobs.
In this tutorial, we learn about fg and bg commands to manage jobs in Linux.
The processes that have been stopped by some interrupt signal can be continued in the background with bg command.
$ nautilus ^Z + Stopped nautilus
This process has been stopped with
ctrl+z interrupt signal. The stopped processes can be checked with jobs command. But before checking, let us create another job and interrupt it with stop signal.
$ jedit 9:22:28 AM [main] [warning] jEdit: inifPLAF failed to set required l&f 9:22:29 AM [main] [warning] jEdit: inifPLAF failed to set required l&f ^Z + Stopped jedit $ jobs - Stopped nautilus + Stopped jedit
You can see that the status of the jobs is stopped. The plus sign (+) indicates the current job. Minus sign (-) refers to the previous job. Now, to run the stopped job in the background, we use bg command. By default, if no argument is given, bg runs the current job in the background.
$ bg + jedit &
$ jobs + Stopped nautilus - Running jedit &
The bg command can take the job number as argument. The job number is indicated in the square brackets in the output of jobs.
In the above example, the job number of nautilus is 1. So now we use this job number to run the job in the background. The
% sign is required for indicating the job number.
$ bg %1 + nautilus & $ jobs - Running nautilus & + Running jedit &
The bg command can also refer to a job by its name. For example
%String refers to a job whose name begins with the specified string and
%?String refers to a job whose name contains the specified string.
For illustration, we have two stopped jobs.
$ jobs + Stopped nautilus - Stopped jedit $ bg %nau + nautilus & $ jobs - Running nautilus & + Stopped jedit $ bg %?ed + jedit & $ jobs - Running nautilus & + Running jedit &
The fg command is like bg command except that instead of sending a command in the background, it runs them in the foreground and occupies the current terminal and waits for the process to exit.
# jobs - Stopped makewhatis + Stopped vi
Without any argument, fg will run the current job in the foreground (vi in this case).
# fg vi
As the command is running in the foreground, we don't get back the terminal until command exits. So, jobs command will now show only one job as vi will exit by now.
# jobs + Stopped makewhatis # fg %1 makewhatis # jobs
No remaining job. Like bg,
%?String work for fg as well.
# jobs - Stopped makewhatis + Stopped vi # fg %v vi # fg %?what makewhatis
In this tutorial, we learned how to job control using fg and bg command using some examples. I hope you enjoyed and please leave your suggestions in the below comment section.