5

I've seen a few examples out there but not been able to work them to my situation.

I have a script that calls a long running command, but I want to periodically (say every 1s) get the status of that call. For example:

#!/bin/bash

curl localhost:9200/my_index/_forcemerge?max_num_segments=2 &

while [ command is running ]; do
  curl -XGET localhost:9200/_cat/shards/my_index?v&h=index,shard,prirep,segments.count
  sleep 1
done

echo "finished!"

Is it possible to get the status of the child process in this way?

Edit: Clarifying what I'm actually doing. It's actually two curl commands to an Elasticsearch cluster. The long running command merges data segments together, the "status" command will get the current segment count.

3
  • You can only get the status of that long running command only after it completes! need more information for this, is the command.sh runs multiple commands on the background or just one command only? and how much time it takes on a average for it to complete Commented Jun 20, 2016 at 9:08
  • Yes this is possible, but you are not clear an what you mean by the status? Are you talking about completion? Which part of your examples is the one that you need help with? The while [ command is running ] part of the /script/that/gets/status.sh part? Commented Jun 20, 2016 at 9:13
  • Ok, so to clarify, the long running command is a curl command. Normally takes about 10 minutes. The status, is the status of the merge called by the curl command (it'll actually be another curl command). Commented Jun 20, 2016 at 9:16

1 Answer 1

11

I think that the safest way of doing this is to save the process ID of the child process and then periodically check to see if this is still running:

#!/bin/bash

mycommand &
child_pid=$!

while kill -0 $child_pid >/dev/null 2>&1; do
    echo "Child process is still running"
    sleep 1
done

echo "Child process has finished"

The variable $! will hold the process ID of the last process started in the background.

The kill -0 will not send a signal to the process, it only make kill return with a zero exit status if the given process ID exists and belongs to the user executing kill.

One could come up with a solution using pgrep too, but that will probably be a bit more "unsafe" in the sense that care must be taken not to catch any similar running processes.

Sign up to request clarification or add additional context in comments.

2 Comments

I have found kill -0 to exhibit seldom strange side-effects. Better to check if /proc/$pid is a directory. Good answer nonetheless.
@LinusKleen Please explain. Also, relying on /proc existing will make a script inherently non-portable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.