问题
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