0

In bash, I would like to run a background process, do something in loop while the process is running, and once the process stopped I would like to get its return code.

Here is what I have so far:

my_build_command
build_pid=$!
sleep 1
while [[ -d /proc/$build_pid ]]
do
    # Do something...
    sleep 1
done

# HOW TO GET THE RETURN CODE OF build_pid?

Is it possible to achieve what I want?

Elad Weiss
  • 3,662
  • 3
  • 22
  • 50
  • 1
    have you seen https://stackoverflow.com/questions/1570262/shell-get-exit-code-of-background-process – jandob Sep 14 '17 at 12:22
  • @jandob I haven't. Will look now. – Elad Weiss Sep 14 '17 at 12:28
  • 1
    Running the command in the background just so you can spin lock in a loop while waiting for it to finish is an odd solution to the problem. Just don't run it in the background. – tripleee Sep 14 '17 at 12:44
  • @tripleee am I XY-ing? – Elad Weiss Sep 14 '17 at 14:22
  • There are obviously legitimate reasons to background something, maybe you do perform something useful in the loop but then maybe mention this in the question even if you want to keep the irrelevant code out of the question. – tripleee Sep 14 '17 at 14:25
  • @tripleee right. Thanks for the tip. Anyway the answered question is exactly what I want. Surprised I didn't see it in search. – Elad Weiss Sep 14 '17 at 14:31

2 Answers2

2

wait $pid does return the return code of the corresponding background process

#!/usr/bin/env bash

(sleep 2; true) &
background_process1_pid=$!
(sleep 2; false) &
background_process2_pid=$!

echo "doing something"

wait $background_process1_pid
echo "background_process1 return code: $?"

wait $background_process2_pid
echo "background_process2 return code: $?"
jandob
  • 651
  • 5
  • 14
0

return code of previously executed program is given by echo $?.

In your case you might want to get the value before using sleep 1

TDk
  • 1,019
  • 6
  • 18