bashsyntax

Beginning bash writer struggles with if test


I have a rather simple bash script which is:

#!/bin/bash -xe
source /reTech/REB3bastionscripts/setup/setenv.sh
echo "##### Begin check/create reportuser   #####################################################"
if [ $REPORT_DB_ENDPOINT != none ]; then
  user_exists=$(psql -U $REPORT_DB_USER -h $REPORT_DB_ENDPOINT -d $REPORT_DB -c "SELECT rolname FROM pg_roles WHERE rolname='reportuser'" | grep reportuser -c)
  if [ "$user_exists" == "1" ]; then
    echo Reportuser exists already in $REPORT_DB database. Resetting password and updating permissions...
  else
    echo creating user reportuser for $REPORT_DB
  fi
fi
if [ !$GRAFANA_DB_ENDPOINT != none ]; then
  user_exists=$(psql -U $GRAFANA_DB_USER -h $GRAFANA_DB_ENDPOINT -d $GRAFANA_DB -c "SELECT rolname FROM pg_roles WHERE rolname='reportuser'" | grep reportuser -c)
  if [ "$user_exists" == "1" ]; then
    echo Reportuser exists already in $GRAFANA_DB database. Resetting password and updating permissions...
  else
    echo creating user reportuser for $GRAFANA_DB
  fi
fi
echo "##### End check/create reportuser   #####################################################"

and no matter which permutations I try for the if statement, it always stops after showing what the value of the local variable user_exists contains but never executes the next step. The result is:

##### Begin check/create reportuser   #####################################################
+ '[' psql-reb3az-devaz-reportdbserver.postgres.database.azure.com '!=' none ']'
++ grep reportuser -c
++ psql -U rebotics -h psql-reb3az-devaz-reportdbserver.postgres.database.azure.com -d report -c 'SELECT rolname FROM pg_roles WHERE rolname='\''reportuser'\'''
+ user_exists=0

I'm kindly asking for help here. Thanks. Wolfgang


Solution

  • The -e on the bash command line tells the shell to terminate when any command it executes exits with a non-zero value.

    When the grep ... -c does not match reportuser it exits with a 1, so the shell stops running. Note that for pipelines, only the last command's status is considered.

    To fix, here are a couple of options:

    • remove the -e from the shell (on the shebang, #!, line at the top)
    • add || true after the grep