Home > database >  BASH: the script quits without an error after an IF condition (possible bug?)
BASH: the script quits without an error after an IF condition (possible bug?)

Time:06-29

I have the following code:

DOMAIN="mydomain.net"
if [ "${DOMAIN}" != "null" ]; then
SSL_CUSTOM=$(echo ${DOMAIN}| grep -c 'myapi.com')
fi
echo $SSL_CUSTOM

This should simply echo 0 in the output, BUT it seems to exit after the SSL_CUSTOM condition line without throwing an exit code.

Here's the debug output:

  DOMAIN=mydomain.net
  '[' mydomain.net '!=' null ']'
   echo mydomain.net
   grep -c myapi.com
  SSL_CUSTOM=0

I could really use an advice what am I doing wrong here. I spent hours on trying to track down the issue in this simple code.

Thanks

CodePudding user response:

I'm not really sure what you are trying to accomplish, so I will fill the gaps with guesses. You have an echo at the end, giving something like 0 or 1. You are also mentioning exit codes. I'm guessing that you want

exit $SSL_CUSTOM

as your last line.

CodePudding user response:

To follow up on my comment with an answer:

SSL_CUSTOM=$(echo ${DOMAIN}| grep -c 'myapi.com' || true)
# ...............................................^^^^^^^

That lets grep -c do what it does, but if no matches are found, the exit status of the pipeline will be "success"


grep exit status demo:

$ seq 1 8 | grep -c 0
0
$ echo $?
1
  •  Tags:  
  • bash
  • Related