So it could have been anything, from COBOL via Algol and FORTRAN to Python and Ruby. Be glad that it did anything at all other then swamping you in error messages
I see you are stuck to the indirect testing of $? instead of direct testing how the program exited.
Now the only thing I believed you on your word is that the program psql returns a non zero status in those cases where you think it should. I have no Postgre (I only know the word Postgress, is that different?) knowledge, but looked into your script. Do not await from me that I correct you when the return codes are different from what you think. I take it for granted that you read the psql documentation thouroughly.