tags:

views:

90

answers:

3

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 ?

+5  A: 

Try this:

if [ $? -eq 0 ]

When running the script use the -x option which prints out each command being executed with actual values. Its very useful for debugging. You'll get to see what is compared with what, what is passed to which command.

$sh -x prg.sh

or

$bash -x prg.sh
codaddict
Thanks. I have to think in bash and in not C, java, perl... with kind of `if true`
Luc M
+2  A: 

[ $? ] is equivalent to [ -n $? ] which will check whether the expansion of $? is a string of nonzero length, which will always be true since $? expands to an exit status which will never be the empty string. In order to check whether a value is zero or not use [$? -eq 0] or (( $? )).

It is besides better to use:

if psql -f sql/test_connection.sql > /dev/null 2>&1
then
   echo "OK"
else
   echo "Doudh!!"
fi

Which will run the command and execute the then part if the exit status of the command is zero or the else part if it is nonzero.

Bart Sas
+3  A: 

Note that if you just pass $? to test (another name for [), that will expand to the string 0 or 2 depending on whether the command was successful. When test is passed a string it just tests if the string is non-empty. In this case, it will always return 0 (true), as both of those strings are non-empty.

What you probably want to do is just use the return value of psql as the argument to if directly, without having to refer to it using $?:

if psql -f sql/test_connection.sql > /dev/null 2>&1
then
   echo "OK"
else
   echo "Doudh!!"
fi

Or, you could test $? against 0 directly

if [ $? -eq 0 ]
then
   echo "OK"
else
   echo "Doudh!!"
fi
Brian Campbell
+1: I feel this explains it the best.
Platinum Azure