RedEyed
RedEyed

Reputation: 2135

Return code of background process bash

How to get return value of background process? If I do this, I will get 0

#!/bin/bash
SomeCommand&
echo $?

output: #~0

But if I try

SomeCommand
echo $?

output: #~255

I read, that wait command, but if I do that

SomeCommand$
wait $!
echo $?

I cannot run next command, if the previous command is not completed.

Upvotes: 2

Views: 4724

Answers (2)

Oleg Andreev
Oleg Andreev

Reputation: 21

    #!/bin/bash
    command1 &
    commandN &
    for job in $(jobs -p)
    do
       wait $job
       echo $?
    done

Upvotes: 0

anubhava
anubhava

Reputation: 785126

wait command waits for a given background job to complete. Use it like this:

( sleep 5; exit 4 ) &
wait $!

ret=$?
echo $ret
4

$! represents process id of the most recent background job.

In your case you can do:

SomeCommand &
wait $!
echo $?

To start multiple background jobs and retrieve their exit statuses later, save the value of $! after you start each job.

( sleep 5; exit 4 ) & b1_pid=$!
( sleep 5; exit 21 ) & b2_pid=$!

# More code

wait $b1_pid
b1_exit=$?
wait $b2_pid
b2_exit=$?

Upvotes: 7

Related Questions