Skip to content

Instantly share code, notes, and snippets.

@vijayganeshpk
Created June 16, 2025 09:02
Show Gist options
  • Save vijayganeshpk/d093b2854b42726d59abaa97024b5ecd to your computer and use it in GitHub Desktop.
Save vijayganeshpk/d093b2854b42726d59abaa97024b5ecd to your computer and use it in GitHub Desktop.
Script to easily provision application specific new database with associated user and password for PostgreSQL
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <database_name> <username> <password>"
exit 1
fi
# Assign arguments to variables
DB_NAME=$1
DB_USER=$2
DB_PASSWORD=$3
# Execute PostgreSQL commands
psql -U postgres <<EOF
-- Step 1: Create the database
CREATE DATABASE $DB_NAME;
-- Step 2: Create the user
CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
-- Step 3: Grant ownership of the database to the user
ALTER DATABASE $DB_NAME OWNER TO $DB_USER;
-- Step 4: Grant all privileges on the database to the user
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
-- Step 5: Connect to the database and grant schema permissions
\connect $DB_NAME
-- Grant privileges on the public schema
GRANT ALL ON SCHEMA public TO $DB_USER;
GRANT CREATE ON SCHEMA public TO $DB_USER;
EOF
echo "Database '$DB_NAME' and user '$DB_USER' have been successfully created with the specified permissions."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment