The other day I was sitting in on a presentation by a co-worker. He was running a job that usually takes a while and and used the bg and fg commands. I was familiar with these commands but have not used them in a while.

Needless to say if you need a refresher or just learning this is how they work:

In this example I am using a simple while loop to play around with this.



while [ ${NUM} -gt 0 ]

echo "Just a Job"


Execute the script.

 # ./ > num.out 

Press control-z to suspend the job.

[1] + Stopped                  ./ > num.out

Your prompt will come back .. and execute the jobs command.
As you will see the job is stopped.

# jobs
[1] + Stopped                  ./ > num.out

Now use the bg command to send the job to the background. If you execute the jobs command you will see the job us no longer in a “Stopped” state but is now running in the background. NOTE: jobs -l will show you the PID.

# bg
[1]     ./ > num.out&
# jobs
[1] +  Running                 ./ > num.out
# jobs -l
[1] + 22495      Running                 ./ > num.out

To kill job # 1 simply kill that job.

# kill %1

Or you can bring it back to the foreground by executing the fg command and wait for it to finish or control-c to kill it.

# fg
./ > num.out