在外壳程序脚本中使用psql创建数据库以用户名作为数据库名称 [英] create database using psql in shell script takes username as db name

查看:130
本文介绍了在外壳程序脚本中使用psql创建数据库以用户名作为数据库名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我用来在Shell脚本中创建数据库的命令

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

抛出错误

FATAL:  database "POSTGRES_USER" does not exist

如果我打印$ database和$ POSTGRES_USER它们显示正确的值,但是当此命令由于某种原因运行时,用户名将作为数据库名称传递。

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

}

从- https://github.com/mrts/docker-postgresql-multiple-databases / pull / 10 / files

推荐答案

您没有使用 psql 终端正确。使用长格式的选项时,您需要在选项及其值之间使用 = 符号。

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.

考虑:

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

这篇关于在外壳程序脚本中使用psql创建数据库以用户名作为数据库名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆