0

I have a script that execute some process and return a number based on the job status. This script is triggered on the back background.

i.e.

ksh -x myscript.sh 20150102 &

My question is how can I get the return code of the background process? Is there a way to get return code like for exit code $?

1
  • Try wait.
    – muru
    Commented Feb 2, 2015 at 15:02

1 Answer 1

3

Use wait:

# Start the job:
ksh -x myscript.sh 20150102 &

# Save its process ID
job_pid=$!

# Do some other stuff in the meantime
asdf ghjk
zxcv qwer

# Later, when you want to know what its exit status was:
wait $job_pid
if [ $? -ne 0 ]; then
    echo "Something may have gone wrong" >&2
else
    echo "The world is perfect." >&2
fi

In this context, I'm considering "return code" and "exit code" synonymous. If you mean the terms to have different meanings from each other then I've misunderstood you, but I can't think what the difference might be.

5
  • In my case the exit code doesn't reflect return code. My script triggers some job remotely nd gets return code from the remote process. So even if the remote code was a failure, I would still get "$?" return 0.
    – Sas
    Commented Feb 2, 2015 at 15:13
  • What do you mean by "return code" and what do you mean by "exit code"? They mean the same thing to me. If I ran something that failed, I would expect a non-zero exit status which is to say a non-zero $?. You mean something different than that by "return code" and/or "exit code"?
    – Celada
    Commented Feb 2, 2015 at 15:16
  • Ok I think I was confused with return code being diff from exit code. But if I am spawning multiple background process how can I get return/exit code for each one of them?
    – Sas
    Commented Feb 2, 2015 at 15:24
  • You can get the exit status of each one of them as per my answer using wait!
    – Celada
    Commented Feb 3, 2015 at 1:10
  • Please not that /bin/sh does not handle wait the same as /bin/bash. It does not report the PID return code as its own upon state change of the PID. Commented Sep 20, 2022 at 18:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .