davidshen84 davidshen84 - 1 month ago 7
Bash Question

How to create a job in shell script?

I know that execute a command and add

&
to the end would create a job and make the command execute in background.

Now I want to create a job in a bash shell. I tried

#!/bin/bash

my-job &
# some other tasks


Then I executed
jobs
, but I got no output. However,
ps aux
does show
my-job
is running in the background.

I want to create a job inside a script, because in some cases I want to bring the job into foreground.

Answer

jobs are usually an interactive shell concept, as there is usually a controlling terminal involved.

A shell script is executed in a non-interactive, non-login session of shell, hence no job control by default.

You can force job control inside a script, by setting:

set -m

inside the script.

From help set:

-m  Job control is enabled.
Comments