2

I have a bash function where I check if a PostgreSQL database already exists.

I capture the output. If database exist PostgreSQL returns the database name as response.

function is_database() {
    local database=$1
    local output=$(sudo -u postgres psql -c "SELECT datname FROM pg_catalog.pg_database WHERE datname=\"$database\";")
    if [[ $output = *"${1}"* ]]
    then
        return 0
    else
        return 1
    fi
}

is_database test

I get the following error:

column "test" does not exist

I am not searching for a table, but a database.

1 Answer 1

6

Use single quotes for string literals:

sudo -u postgres psql \
    -c "SELECT datname FROM pg_catalog.pg_database WHERE datname='$database'"

Your code as it is won't work for database names like has spaces or has'quotes.

Sign up to request clarification or add additional context in comments.

3 Comments

similar sudo -u postgres psql -c "SELECT version();" $dbname : actually try to connect to the DB, and check $? afterwards in the shell
You can go one further and use the --tuples-only option to have psql return just the database name or nothing and not any other dross (like the table header and the footer).
Maybe this is because of my version of psql but this command gives me several psql: warning: extra command-line argument "..." ignored, I replaced it with: echo "SELECT datname FROM pg_catalog.pg_database WHERE datname='$database'" | psql -XtA -U postgres and it worked (-XtA to get only database name as output, empty if not found then).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.