Last Updated: February 25, 2016
·
2.309K
· sheerun

Shell jobs in a pill <3

You can make a job from any process by pressing Ctrl+z.

They suspend by default.

You can list them by jobs builtin:

$ jobs
[1]  + suspended  htop
[2]  - suspended  tail -f log/prod.log | grep Critical

And later resume them with fg:

$ fg        # resume last job
$ fg %1     # resume first job
$ fg %?tail # resume job with tail in name

The %1 is so called job spec that refers to [1] job.

Or put them to background with analogous bg command, or by postfixing any command with an ampersand & (background jobs are just forks that are connected to shell's STDOUT/ERR descriptors).

Foreground jobs listen to keyboard events and signals. Background ones don't. Also, interactive tasks that were put to background are suspended when you interact with shell, so they are not much useful.

You can enable jobs in your shell scripts, by calling set -m builtin:

Enables monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it. Background processes run in a separate process group and a line containing their exit status is printed upon their completion.

You can wait for jobs in background to finish using wait builtin.

Wait for each specified process and return its termination status. Each n may be a process ID or a job speciif a job spec is given, all processes in that job’s are waited for. If n is not given, all currently act processes are waited for

You can also disown any background jobs to make them daemons, or disown -r to do the same thing, but not remove them from jobs.

Without options, each jobspec is removed from the table of active jobs. If jobspec is not present, and neither -a nor -r is supplied, the shell's notion of the current job is used. If the -h option is given, each job-spec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is present, and neither the -a nor the -r option is supplied, the current job is used. If no jobspec is supplied, the -a option means to remove or mark all jobs.

Btw. SIGHUP is sent if you exit any interactive shell, for example by closing an ssh session. There's also nohup builtin, but usually you want to disown it anyway (so it runs as daemon).

Of course you can kill any job (suspended or not) by f.e. kill %1.

BONUS! suspend and put to foreground in single shourtcut (vim <3)

Know any interesting thing about shell jobs? Write a comment :)

1 Response
Add your response

Basics, but still a good reminder.

over 1 year ago ·