1

I have do a search of how to detect the a command success or not in bash. For example: https://askubuntu.com/questions/29370/how-to-check-if-a-command-succeeded/29379#29379 Some one suggested that using $? to detect a command is success or not.

I want do a lot of task and check if the task is works OK.

At first, I do run and check one by one. It is in a serial way.

# first
./a.out
if [ "$?" -ne "0" ]; then
    echo "code error!"
fi
# second
./b.out
if [ "$?" -ne "0" ]; then
    echo "code error!"
fi
# third
./c.out
if [ "$?" -ne "0" ]; then
    echo "code error!"
fi

There is no denpency between task, so I want to transfer the script to a parallel way. I want submit the command in the background and do the check after command the finished. I want something like follow

# submit all task to back ground
./a.out &
./b.out &
./c.out &

# wait they all finished ...
# wait a
# wait b
# wait c

# do some check ...
# check a
# check b
# check c

I don't know how to realize that ...

Cound any one help me? Thank you for your time.

1
  • 1
    BTW, it's rarely necessary to compare $? like that. Just use the exit status directly, e.g. if ! ./a.out; then ... Commented Nov 6, 2019 at 13:44

1 Answer 1

2

From man wait(1):

EXIT STATUS top

   If one or more operands were specified, all of them have terminated
   or were not known by the invoking shell, and the status of the last
   operand specified is known, then the exit status of wait shall be the
   exit status information of the command indicated by the last operand
   specified. [...]

It would look like this:

# submit all task to back ground
./a.out &
apid=$!
./b.out &
bpid=$!
./c.out &
cpid=$!

# wait they all finished ...
wait "$apid"
aret=$?
wait "$bpid"
bret=$?
wait "$cpid"
cret=$?

# do some check ...
if ((aret)); then
   echo a failed
fi
if ((bret)); then
   echo b failed
fi
if ((cret)); then
   echo c failed
fi
Sign up to request clarification or add additional context in comments.

1 Comment

With regard to Toby Speight's comment, you can use if ! wait "$apid"; then echo a failed; fi if you care about the exact exit code.

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.