0

I came across the script with if-else branch with a particular command succeed or not like this:

pg_ctl -D /var/lib/pgsql/data -w promote
if [ $? -ne 0 ]; then
   echo: failure
   exit 1
else
   echo: succeed
   exit 0
fi

It looks straight forward. But if the postgresql server it wanted to promote is already running as primary, it will also throw out an error code=1 and error message containing 'is not in standby mode'. So it is okay if this error occurs, but error code=1 or $? -ne 0 produces a false positive. I want to just take this particular error out as another successful outcome, and how can I achieve it?

George Y
  • 528
  • 6
  • 16

1 Answers1

0

There is no straight forward bash variable like $? to catch the exact error message, however, it is possible to store the outcome in a text file for analysis. In this case, the script is like this:

pg_ctl -D /var/lib/pgsql/data -w promote &> promote_return
if [ $? -ne 0 ]; then
   if [ `grep -c 'is not in standby mode' promote_return` -ne 0 ]; then
     echo okay: no need to promote twice.
     exit 0
   else 
     echo failure: please check the file promote_return for error message.
     exit 1
   fi
else
   echo succeed
   exit 0
fi
George Y
  • 528
  • 6
  • 16