Created
November 24, 2024 06:13
-
-
Save darcyliu/d488bd3f406ff55977917d195e91a90a to your computer and use it in GitHub Desktop.
Create/Delete databases and users in PostgreSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if the correct number of arguments are provided | |
if [ "$#" -ne 2 ]; then | |
echo "Usage: $0 <database_name> <user_name>" | |
exit 1 | |
fi | |
# Command-line arguments | |
DB_NAME="$1" | |
DB_USER="$2" | |
# Generate a random password | |
DB_PASSWORD=$(openssl rand -base64 12) | |
# Create the database | |
psql -U postgres -c "CREATE DATABASE $DB_NAME;" | |
# Create the user with the generated password | |
psql -U postgres -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';" | |
# Grant all privileges on the new database to the new user | |
psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;" | |
# Output the generated password | |
echo "Database '$DB_NAME' and user '$DB_USER' created successfully." | |
echo "Generated password for user '$DB_USER': $DB_PASSWORD" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if the correct number of arguments are provided | |
if [ "$#" -ne 2 ]; then | |
echo "Usage: $0 <database_name> <user_name>" | |
exit 1 | |
fi | |
# Command-line arguments | |
DB_NAME="$1" | |
DB_USER="$2" | |
# Delete the database | |
psql -U postgres -c "DROP DATABASE IF EXISTS $DB_NAME;" | |
# Delete the user | |
psql -U postgres -c "DROP USER IF EXISTS $DB_USER;" | |
echo "Database '$DB_NAME' and user '$DB_USER' have been deleted." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment