1
#!/bin/bash
RET=0
export RET
{
ssh -q -t  user@host <<EOF
echo "hello there "
exit 10
EOF
RET=$?
echo "Out is" $RET
} &
echo "RET is $RET"
################## End

I get RET 0 OUT is 10

How can I get correct exit status code in outer block. I need to see exit code 10.

  • Remove the &. It is running the first part in background. – Jakuje Oct 3 '16 at 18:41
5

You either need to run the command in the foreground

$ (exit 10)
$ echo $?
10

Or if it runs in the background, explicitly wait for it:

$ (sleep 3; exit 10) &
$ wait %%                      # %% refers to the current (last) job
$ echo $?
10

Or by specifying the process ID instead of the job number for wait:

$ (sleep 3; exit 10) & pid=$!
$ wait $pid                    # $! holds the PID of the last background process
$ echo PID $pid exited with code $?
  • @grochmal, seems to work, dash -c '(sleep 1; exit 11) & wait %1 ; echo $? ' prints 11 for me. – ilkkachu Oct 3 '16 at 19:36
  • Interesting, I always thought that dash has no job control. Still there are shells out there without job control, thanks for the edit. (removing obsolete comment) – grochmal Oct 3 '16 at 20:18
  • 1
    @grochmal "job control" seems to be a loaded term that doesn't always mean what we think. For bash, job control refers to being able to after-the-fact stop a process and put it in the background and return it to the foreground. Even in situations without "job control" in bash you can still run background jobs and wait for or kill things by job ID – Eric Renouf Oct 4 '16 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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