Running Linux Commands in Background and Foreground

In Linux, one can run processes in the background to free up the terminal. Longer processes can be run in the background while the user can work on other tasks.

Lets open gvim, a gui version of the vim.

gvim

Since by doing above, our terminal is now busy serving the process gvim and we can't use the terminal for anything else. Lets try now to free up the terminal by suspending the current process. We can do this by pressing ctrl+z .

➜ ~ gvim
^Z
[1] + 28297 suspended gvim

By press ctrl+z, we have to suspend the process and now our terminal is free to use. Lets type command "jobs" now. jobs will give us a list of current processes which are active in current terminal now.

➜ ~ jobs
[1] + suspended gvim

But how about if we want to run the gvim and also free up the terminal so that we can use it for tasks. We can do this by starting the suspended process in background.

The syntax to do that is "bg %<jobno>". Here jobno is the serial number of the job "[1] + suspended gvim" which is 1 in our case.

➜ ~ bg %1
[1] + 30663 continued gvim

Now lets do jobs again and see what we get.

jobs
➜ ~ jobs
[1] + running gvim

Lets say we want to bring the job from background to foreground. Remember once the job is in foreground, our terminal command prompt can't be used or anything else. To bring the job to foreground, the command is fg %.

Lets run following command

fg %1
➜ ~ fg %1
[1] + 2894 continued gvim

We can run ideally as many as background processes as we want. Of course in that case memory will be an issue.Below example shows two processes.

[1]  - suspended  gvim
[2]  + suspended  sleep 1000

We can bring one of them to the foreground and run the other in the background. Lets push 2nd to background and first to foreground.

We got following messages.

➜ ~ bg %2
[2] - 4111 continued sleep 1000
➜ ~ fg %1
[1] - 4019 continued gvim

I hope you got the idea from above usage of bg and fg commands.