Score:0

Setting Up PostgreSQL DB with bash script using variables from .env file

ca flag

I'm trying to set up PostgreSQL with a bash script which takes the variables from an .env file.

My code -

#!/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;"

If I echo the variables before running the postgres database creating lines like the following, they output correct variables read from the .env file.

#!/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;"

But after the script is ran, I can't log in with the user and password combination using -

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

After entering the password, it shows -

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

My .env file looks like this -

#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
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.