Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I launch a process in background and check when it ends within a bash script? My idea is a script like this:

launch backgroundprocess &
while [ Process is running ];do
   echo "PROCESS IS RUNNING\r"
done;

echo "PROCESS TERMINATED"
share|improve this question

migrated from serverfault.com May 22 '13 at 16:53

This question came from our site for system and network administrators.

4 Answers 4

up vote 16 down vote accepted

The key is the "wait" command:

#!/bin/bash

/my/process &
/another/process &
wait
echo "All processes done!"
share|improve this answer
1  
Benefit of this: it does NOT burn CPU time with an infinite loop running all the time.... ;) –  Pascal Schmiel May 22 '13 at 12:47
    
The disadvantage of this is that you can't do anything else while you are waiting, such as indicating progress to the user. Only cuonglm's solution allows you to do this. –  Mark Booth Apr 28 at 10:30

With wait you can have the granularity you need:

sleep 1 &
PID1=$!
sleep 2 &
PID2=$!

wait $PID1
echo PID1 has ended.
wait
echo All background processes have exited.
share|improve this answer

Here is one way to do it:

launch backgroundprocess &
PROC_ID=$!

while :; do
  if kill -0 "$PROC_ID" 2>/dev/null
  then
    echo "PROCESS IS RUNNING"
  else
    echo "PROCESS TERMINATED"
    exit 1
  fi
done
share|improve this answer
    
Thanks, this is definitely the only answer which answers my interpretation of the original question (and the reason why I ended up looking at this question) –  Mark Booth Apr 30 at 14:48

You can run your process with nohup and write shell script to read nohup.out file which nohup uses to log .

  nohup command &
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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