I have the following bash script:
#!/bin/sh
psql -U postgres -c "CREATE DATABASE test TEMPLATE template0;"
if [ $? -eq 0 ]; then
echo OK
else
if [ $? = 'ERROR: database "test" already exists' ]; then
echo OK
else
echo FAIL
fi
fi
It's currently failing with the following error:
testbox:/tmp# sh test.sh
ERROR: database "test" already exists
FAIL
I'm not sure where I've gone wrong. I need it to return "OK" for this specific error. Any other errors should print out a FAIL. Can you tell me where I've gone wrong?
Thanks.
EDIT 1
I've modified the code to capture the output, not just rc:
#!/bin/bash
output=$(psql -U postgres -c "CREATE DATABASE test TEMPLATE template0;")
ret=$?
if [[ $ret -eq 0 ]]; then
echo OK
else
if [[ $output == 'ERROR: database "test" already exists' ]]; then
echo OK
else
echo FAIL
fi
fi
But I get this error:
ERROR: database "test" already exists
sh: ERROR: database "test" already exists: unknown operand
FAIL