I want to verify if I can connect to a database (PostgresSQL) into a bash script
I execute the following command (PGUSER, PGDATABASE… are set)
psql -f sql/test_connection.sql > /dev/null 2>&1
When I echo $? it shows 0 if success, 2 if not.
It works fine in a terminal.
When I put it into a bash script the result is always 0 even when the credentials are not correct.
psql -f sql/test_connection.sql > /dev/null 2>&1
if [ $? ]
then
echo "OK"
else
echo "Doudh!!"
fi
Where am I missing something ?
Note that if you just pass
$?totest(another name for[), that will expand to the string0or2depending on whether the command was successful. Whentestis passed a string it just tests if the string is non-empty. In this case, it will always return0(true), as both of those strings are non-empty.What you probably want to do is just use the return value of
psqlas the argument toifdirectly, without having to refer to it using$?:Or, you could test
$?against0directly