3

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?

5

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.

  • 1
    thanks. could you also answer how can I obtain information about a status of a particular job inside of a shell script? – user13107 May 19 '16 at 11:06
  • (i'll accept your answer later in case someone has a better method) by the way, can it happen that the process id gets assigned to some other process by the system, after the original process is done? it could create a confusion then! – user13107 May 19 '16 at 11:21
  • PIDs are recycled, yes. Looking at the issue more generally, to manage groups of processes together, you could use process groups or cgroups, but that feels like it's outside the scope of your question... – Stephen Kitt May 19 '16 at 11:37
0

Like Stephen said, spawning a new shell is probably not what you want to do. You have to run the code in the current shell.

Your code would work by either doing source myscript.sh or declaring your code in a function (which could be in your bashrc or a separate file that is sourced).

myfunction () {
  jobs -l
} 

I used this in my dotfiles, if you're interested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.