3

Following is the command I am using to create database in shell script

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" \
            -c "CREATE DATABASE $database;"

It throws error

FATAL:  database "POSTGRES_USER" does not exist

If I print $database and $POSTGRES_USER they show correct values but when this command runs with some reason the username is passed as the database name.

any clue what I might be missing?

======

function create_db() {
    local database=$1
    local query_databases="select datname from pg_database;"
    local databases=$(echo "$query_databases" | psql -Aqt)
//this do not return any database but I have one db
    database_exist=$(containsElement "$databases" "$database")
    echo $database_exist;

    if [[ "$database_exist" == 1 ]]; then
        echo "Database '$database' exists. Skipping."
    else
        echo "Create Database '$database'"
        psql -v ON_ERROR_STOP=1 --username=$POSTGRES_USER \
             -c "CREATE DATABASE $database;"
    fi

}

taking reference from - https://github.com/mrts/docker-postgresql-multiple-databases/pull/10/files

4
  • 1
    It is a default. If you don't supply a database name, postgres uses the username as a database name. So: you should supply a database name on the commandline. (postgres,or template1) Commented Sep 18, 2019 at 21:34
  • @wildplasser shall I provide the name of the database which does not exists? Commented Sep 18, 2019 at 21:52
  • 2
    You should supply a database name that does exist. (postgres and template1 (almost) always exist) Commented Sep 18, 2019 at 22:09
  • That resolve the issue. Commented Sep 18, 2019 at 22:18

2 Answers 2

1

You need to remove the " in the command.

psql -v ON_ERROR_STOP=1 --username $POSTGRES_USER -c "CREATE DATABASE $database;"

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

1 Comment

I still get the same error, I have updated with my function definition in the question.
1

You are not using psql terminal correctly. When using the long form of option, you need the = sign between the option and its value. Also the double quotes are not needed.

Consider:

psql -v ON_ERROR_STOP=1 --username=$POSTGRES_USER \
        -c "CREATE DATABASE $database;"

1 Comment

I still get the same error, I have updated with my function definition in the question.

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.