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