1

I currently use the technique described in How do I write a bash script to restart a process if it dies? by lhunath in order to restart a dead process.

until myserver; do
    echo "Server 'myserver' crashed with exit code $?.  Respawning.." >&2
    sleep 1
done

But rather than just invoking the process myserver, I would like to invoke such a thing:

 myserver 2>&1 | /usr/bin/logger -p local0.info &

How to use the first technique with a process with pipe?

Community
  • 1
  • 1
Sylva1n
  • 119
  • 1
  • 7

2 Answers2

4

The until loop itself can be piped into logger:

until myserver 2>&1; do
    echo "..."
    sleep 1
done | /usr/bin/logger -p local0.info &

since myserver inherits its standard output and error from the loop (which inherits from the shell).

chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can use the PIPESTATUS variable to get the exit code from a specific command in a pipeline:

while :; do
    myserver 2>&1 | /usr/bin/logger -p local0.info
    if [[ ${PIPESTATUS[0]} != 0 ]]
    then echo "Server 'myserver' crashed with exit code ${PIPESTATUS[0]}.  Respawning.." >&2
         sleep 1
    else break
    fi
done
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • If we want to handle only the myserver failure (PIPESTATUS[0]), I think the chepner's answer is more elegant. If we want to handle the failure of /usr/bin/logger too, then your loop seams better. – mcoolive Sep 10 '14 at 22:26