0

I am executing a Hive query via beeline from a shellscript. Below is a sample of the code: I see that even if connection to Hive Database fails, $? would still return zero as exit code. How can I fetch the exit code/connectivity status from beeline for a use case like below ? I need to stop the execution of shellscript as soon as beeline fails to connect to DB and a proper message should be logged suggesting Hive Connection failed.

beeline -u $HIVE_CONNECTION_STRING  --outputformat=csv2 -f $LOCATION_OF_HIVE_SELECT_QUERY_FILE > QueryResults.csv

if [$? -ne 0]; then 
   echo "Could not connect to DB."
   exit 1
else
   #Do rest of the process since data was fetched from DB successfully above
fi
Nikhil24
  • 51
  • 1
  • 10

2 Answers2

0

I think you have a whitespace - ne where you shouldn't. Try this -ne:

beeline -u $HIVE_CONNECTION_STRING  --outputformat=csv2 -f $LOCATION_OF_HIVE_SELECT_QUERY_FILE > QueryResults.csv

if [$? -ne 0]; then 
   echo "Could not connect to DB."
   exit 1
else
   #Do rest of the process since data was fetched from DB successfully above
fi
Matt Andruff
  • 4,974
  • 1
  • 5
  • 21
  • Thanks Matt. I checked my actual shell script that I am executing and there was no whitespace in '- ne'. It was a typo here, I just fixed it. – Nikhil24 Jan 19 '22 at 05:04
0

You do not need to use $?. Just put the command into the if condition and exchange then and else clause.

if beeline -u "$HIVE_CONNECTION_STRING" --outputformat=csv2 -f "$LOCATION_OF_HIVE_SELECT_QUERY_FILE" > QueryResults.csv
then 
  #Do rest of the process since data was fetched from DB successfully above
else
  echo "Could not connect to DB."
  exit 1
fi

Btw: Always double-quote variables in program arguments.

ceving
  • 21,900
  • 13
  • 104
  • 178