This can get tricky. You need to return ${PIPESTATUS[n]} from the backgrounded job. I do something very similar by creating a function and passing in the command to run as an argument then send the whole thing to the background. NOTE the return statement in the pipe_command() function. This returns the status of $cmd as opposed to your while read line loop. You can background multiple things in a for loop using this technique as well. Hope this helps.
Example:
#! /bin/bash
main()
{
pids=""
myprocess="ssh user@node /bin/bash /etc/init.d/process start"
pipe_command "$myprocess" &
pids+="$! "
watch_pids "$pids"
}
pipe_command()
{
cmd="$1"
$cmd 2>&1 | \
while read line; do
logger -t mytag -p user.err $line
done
return ${PIPESTATUS[0]}
}
watch_pids()
{
pids="$1"
for pid in $pids; do
wait $pid
if [ $? -ne 0 ]; then
logger -t ${tag} -p user.error "CANNOT START (exit code: $?)"
return 2
fi
done
}
main $@
Or perhaps more simply put to your example:
myprocess | while read line; do logger -t mytag -p user.err $line; done ; return ${PIPESTATUS[0]} &
wait
status=$?
if [ $status -ne 0 ]; then
logger -t ${tag} -p user.error "CANNOT START (exit code: $status)"
fi
PIPESTATUSapplies to the most recent foreground pipeline.