1

I have written following function in my bashrc. It checks if a job is running every 5 seconds and sends email when job is finished.

function jobcheck () {
  time=`date`
  jobstatus=`jobs $1`
  while [ 1 ]; do
  if (( ! `echo $jobstatus | grep "Running" | wc -l` )); then
    "sendEmail command to send email"
    break;
  fi
  sleep 5;
  done
}

I want to call this function as below (for job number 2, for exmaple)

jobcheck 2

and proceed to run other commands on the commandline. But the while loop keeps on running and I do not get command prompt.

If I run it as

jobcheck 2 &

Then it gives error that bash: jobs 2 not found

How do I run this function in background?

  • This will depend on the command line mail program you have installed. For example, on FreeBSD, mail is install by default (and you can simply pass a few values to it) but I have no idea what Operating System you are running. – Tigger Mar 16 '17 at 6:23
  • @Tigger I'm using Ubuntu 12.x. I use sendEmail to send email. Sending email part works alright. – user13107 Mar 16 '17 at 6:45
  • 1
    If you want to run a job in the background and get an email when it is done, why not simply use batch? – psusi Mar 16 '17 at 13:08
3

You will have to rewrite your function to be able to do that.

When you start a background job with &, the shell does indeed keep track of that, and you can indeed figure out more information by using the jobs builtin. However, that information is specific to that instance of the shell; if you run your function with & itself, then a separate shell is spawned which is not the shell with the background jobs, and therefore you can't access the information about the original shell's jobs from that separate shell.

However, there's a simple way to fix that:

  • rewrite your function so it runs in terms of process IDs (PIDs) rather than job numbers. That is, have it check whether a process still exists (e.g., by way of parsing ps output, of by checking whether /proc/pid exists)
  • run your new function with %2 rather than 2 as argument. That is, give it the percent sign followed by the job id you want to monitor; the percent sign is used by Bourne shells to replace a job id by the pid of the given job.

With that, it should just work.

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.