How to send a process to the background

Sending a process to the background in Linux is quite easy. All you need is bg, fg, &, and ctrl+Z ( ^Z ).

For this example I will use a simple bash script test.sh I put together to print “Test” every 5 seconds.

#!/bin/bash
#This script will print "Test" every 5 seconds
#
while [ true ]
do
echo "Test at `date`"
sleep 5
done
#End

Now let’s see how it’s done.

[user@abubu root]$./test.sh &
This starts test.sh and sends it to the background. You will be back at shell but should see the “Test” message every 5 seconds.

[user@abubu root]$jobs
[1]+ Running ./test.sh &

The jobs command will print all the background processes. Each process is represented by a number to it’s left. For example, tesh.sh is represented by 1.

[user@abubu root]$fg 1
The fg command will send the test.sh process to the foreground and return control to the shell.

[user@abubu root]$ ./test.sh (hit ctrl+Z (^Z) now)
Test at Tue Jun 3 15:11:38 MYT 2008
[1]+ Stopped ./test.sh

The test.sh process is temporarily suspended.

[user@abubu root]$bg 1
The bg command will send test.sh to the background.

[user@abubu root]jobs
[1]+ Running ./test.sh &

The jobs command will print all the background processes. Each process will be represented by a number to it’s left. tesh.sh is represented by 1.

[user@abubu root]$fg 1
The fg command will send the test.sh process to the foreground and return control to the shell.

That’s it.

3 Responses to “How to send a process to the background”

Author comments are in a darker gray color for you to easily identify the posts author in the comments

  1. Anton Daneyko says:

    What if I’ve started something as
    $ ./long_running_script.sh

    and then I realize I want to do something else, so I want to get the control over the shell back, but at the same time want the script to continue running. So I do

    $ Ctrl+Z
    [1]+ Stopped ./long_running_script.sh

    How do I make it run on the background now? I.e. make it run like I first did
    $ ./long_running_script.sh &

  2. Anton Daneyko says:

    Thanks,
    I recieved your reply just as I was untaring a 20Gb file and instanteniously tried it out.

Leave a Reply

© 2008-2009 The Danesh Project
Powered by Wordpress and made by Guerrilla. Best viewed in Mozilla Firefox