使用 .env 文件中的变量通过 Bash 脚本设置 PostgreSQL DB

使用 .env 文件中的变量通过 Bash 脚本设置 PostgreSQL DB

我正在尝试使用从 .env 文件中获取变量的 bash 脚本来设置 PostgreSQL。

我的代码 -

#!/bin/bash

DB_NAME=$(grep DB_NAME .env | cut -d '=' -f 2-)
DB_USER=$(grep DB_USER .env | cut -d '=' -f 2-)
DB_PASSWORD=$(grep DB_PASSWORD .env | cut -d '=' -f 2-)

echo $DB_NAME;
echo $DB_USER;
echo $DB_PASSWORD;

sudo -u postgres psql -c "CREATE DATABASE $DB_NAME;"

sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';"
sudo -u postgres psql -c "ALTER ROLE $DB_USER SET client_encoding TO 'utf8';"
sudo -u postgres psql -c "ALTER ROLE $DB_USER SET default_transaction_isolation TO 'read committed';"
sudo -u postgres psql -c "ALTER ROLE $DB_USER SET timezone TO 'UTC';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"

如果我在运行 postgres 数据库之前回显变量并创建如下行,它们会输出从 .env 文件读取的正确变量。

#!/bin/bash

DB_NAME=$(grep DB_NAME .env | cut -d '=' -f 2-)
DB_USER=$(grep DB_USER .env | cut -d '=' -f 2-)
DB_PASSWORD=$(grep DB_PASSWORD .env | cut -d '=' -f 2-)

echo $DB_NAME;
echo $DB_USER;
echo $DB_PASSWORD;

sudo -u postgres psql -c "CREATE DATABASE $DB_NAME;"

sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';"
sudo -u postgres psql -c "ALTER ROLE $DB_USER SET client_encoding TO 'utf8';"
sudo -u postgres psql -c "ALTER ROLE $DB_USER SET default_transaction_isolation TO 'read committed';"
sudo -u postgres psql -c "ALTER ROLE $DB_USER SET timezone TO 'UTC';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"

但是脚本运行后,我无法使用用户和密码组合登录 -

psql -h localhost -d mydb -U myuser -p 5432

输入密码后显示——

psql: error: FATAL:  password authentication failed for user "myuser"
FATAL:  password authentication failed for user "mydb"

我的 .env 文件如下所示 -

#WORK_ENV can be local, testing, staging or production
WORK_ENV=local

# django secret key
SECRET_KEY='your-secret-key-goes-here'

# database
DB_NAME=your_db_name
DB_USER=your_db_user_name
DB_PASSWORD=your_db_password
DB_HOST=localhost
DB_PORT=5432

SENTRY_DSN=your-unique-sentry-project-link

相关内容