I use shell job control to kick longer running tasks in to the background so I can continue while they churn through their data.
I can see the jobs I've got running with jobs, for example,
jobs
[2]- Running su - root -c "..." & (wd: /backup/rsnapshot)
[3]+ Running sleep 60 &
and I can control any one of these using the % jobspec syntax, such as fg %su or kill %3.
If I use jobs -l I get the PIDs too:
jobs -l
[2]- 31736 Running su - root -c "..." & (wd: /backup/rsnapshot)
[3]+ 2269 Running sleep 60 &
Using bash I've got jobs -x, but this isn't POSIX. Is this the only way to translate these % jobspec values into PIDs, or is there a sensible (better) alternative approach? What about for other shells?
jobs -x echo %3
2269
My target use case is for the % jobspec to be expanded transparently on the command line into the corresponding PID, so that in a command such as this the %2 would be seen by the command as 31736
pidtree %2 # pidtree 31736
This can be handled as jobs -x pidtree %2 but that's not as elegant or convenient.
I'd like at least one answer targeting bash, but contributions for other shells with job control are welcome, particularly if you have a POSIX solution.
jobs -lorjobs -xcan be piped to a bash action to get informations over the job like openned files & so on ; depending of your final objectives . for examplecat /proc/25943/task/25943/statmand so on... Please edit the question with an use case. – francois P Aug 04 '20 at 11:07cat /proc/$(jobs -l | sed 's/.*+ \(.*\) [A-Z].*/\1/; /[^0-9]/ d ')/statmanswered2451 1109 398 219 0 742 0so sed substitution worked (not optimized at all to let you understand) – francois P Aug 04 '20 at 11:21jobs -lorjobs -xis part of the Bourne Shell since before bash exists. Is your question about non-conforming shells? – schily Aug 04 '20 at 11:22jobs -x, because the SUS does not. (-: – JdeBP Aug 04 '20 at 12:06jobs -l | perl -lne '/\[(\d+)\][-+]?\s+(\d+)\s+(\S+)\s+(\S.*)/; print "jobID:$1\tPID:$2\tstate:$3\tcomm:$4"'? – terdon Aug 04 '20 at 12:33jobs -xwasn't recognised bydashand it's not POSIX – Chris Davies Aug 04 '20 at 12:45%jobspec to be translated (transparently if possibly) to the PID – Chris Davies Aug 04 '20 at 12:59