How to get process ID of background process?
You need to save the PID of the background process at the time you start it:
foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID
You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.
You can use the jobs -l
command to get to a particular jobL
^Z
[1]+ Stopped guard
my_mac:workspace r$ jobs -l
[1]+ 46841 Suspended: 18 guard
In this case, 46841 is the PID.
From help jobs
:
-l Report the process group ID and working directory of the jobs.
jobs -p
is another option which shows just the PIDs.