May 08, 2013

bg, fg and jobs Linux Commands

Every command you give is a job that is executed. A job can be suspended, placed in the background, moved back to the foreground or terminated.

While running a job you can        Shortcut
---------------------------            ----------
suspend a job                    ctrl+z

terminate a job                    ctrl+c

Function                            Command
--------                            ------------
Move a suspended job to the foreground        fg

Continue a suspended job in the background    bg

List all jobs                            jobs

Kill a job (%N where N is the job number)    kill %N && fg

Start a job directly in the background            command &

When you execute a unix shell-script or command that takes a long time, you can run it as a background job.

1. Executing a background job

$ find . -name "*.aud" -mtime +120 -exec rm {} \; &

2. Sending the current foreground job to the background using CTRL+Z and bg command
    step 1.Press 'CTRL+Z' which will suspend the current foreground job.
    step 2.Execute 'bg to' make that command to execute in background.

Press ‘CTRL+Z’
$ bg

3. View all the background jobs using jobs command.

$jobs

jobs    : lists the jobs that you are running in the background and in the foreground

jobs -p : list only the PID of process group leader

jobs -l : list only jobs that have change status since last notified by their status

jobs -r : resrict output to running jobs

jobs – s : restrict output to stopped jobs

4. Taking a job from the background to the foreground using fg command

$ fg

When executed without arguments, it will take the most recent background job to the foreground

No comments:

Post a Comment