create database using psql in shell script takes username as db name

淺唱寂寞╮ 提交于 2019-12-11 08:14:13

问题


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


回答1:


You need to remove the " in the command.

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




回答2:


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;"


来源:https://stackoverflow.com/questions/58000907/create-database-using-psql-in-shell-script-takes-username-as-db-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!