Shell Jobs Command – Why Does the Jobs Command Not Work in Shell Script?

job-controljobsshellshell-script

If I run jobs -l on command prompt it shows me the status of running jobs but if I run below file ./tmp.sh

#! /bin/bash
jobs -l

It shows empty output.

Why is that and how can I obtain information about a status of a particular job inside of a shell script?

Best Answer

jobs

shows the jobs managed by the current shell. Your script runs inside its own shell, so jobs there will only show jobs managed by the script's shell...

To see this in action, run

#!/bin/bash
sleep 60 &
jobs -l

To see information about "jobs" started before a shell script, inside the script, you need to treat them like regular processes, and use ps etc. You can limit yourself to processes started by the parent shell (the shell from which the script was started, if any) by using the $PPID variable inside the script, and looking for processes sharing the same parent PID.

Related Question