Tip: job control in the shell

In an interactive shell there is something that is called "job control".
If you put something in the background with an & then it becomes a "job".
For example

sleep 60 &

You can display the jobs with

jobs

The first job gets the jobnr 1.
You can kill any of them with

kill %jobnr

e.g. kill %1

Or you can pull one of them to the foreground by

fg %jobnr

Just
fg
pulls the most recent job.

How can you do the opposite, place the foreground task into the background?
For the example

sleep 60

First you must stop it. This is done with

Ctrl-Z

It sends a SIGSTOP to the foreground task, and it remains in a stopped (paused) state.
(Compare with Ctrl-C that sends a SIGINT.)
Now you have the command prompt back.
And you can list it with

jobs

And now you can put it to the background with

bg

(Or bg %jobnr if you have several running or stopped jobs.)
Of course you can put a stopped job into the foreground with

fg

Say you started a vi and would like to run some shell commands. Well, in some cases you can start another shell in another terminal. But also you can stop the vi with
Ctrl-Z
run your commands, and continue the editing with
fg

What happens if you continue the vi with
bg
?
Well, vi is not made for running in the background.
You can try and find out what happens...
Remember, any time you can pull it to the foreground.

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.