Issue
I am using shell
trying to capture list of background jobs:
sleep 11 | tee log_1.txt &
sleep 12 | tee log_2.txt &
jobs -p # this returns PIDs
X=$(jobs -p)
echo ${X}
Then I start it like this: sh ./script.sh
But for some reason I get nothing.
Trying to debug it I see that jobs -p
actually returns the list of items.
Something like X=$(ls -al)
also works as expected and the content is captured.
Solution
Your code works fine in bash
:
$ bash myfile
10715
10717
10715 10717
$
But it does fail in dash
, which is probably what your sh
is:
$ dash myfile
11048
11046
$
(see Why does my bash code fail when I run it with sh?).
dash
is within its rights to behave this way (and Bash is arguably wrong) because POSIX specifies that "The jobs utility shall display the status of jobs that were started in the current shell environment", and you have created a new shell environment through your use of the subshelling $(...)
.
If you want to do it in a sh
compatible way you can redirect to a temp file and read that instead. Alternatively, you can collect the pids of each started background job using $!
.
Answered By - that other guy Answer Checked By - Marie Seifert (WPSolving Admin)