Score:0

How to catch the error output in shell when error code is not enough?

vn flag

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?

Score:0
vn flag

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
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.