#!/bin/bash # Prompt for container name read -p "Enter PostgreSQL container name: " CONTAINER_NAME # Check if container is running if [ "$(docker ps -q -f name=$CONTAINER_NAME)" = "" ]; then echo "Container $CONTAINER_NAME is not running!" exit 1 fi echo "Using container: $CONTAINER_NAME" # Prompt for PostgreSQL root credentials read -p "Enter PostgreSQL root username: " PGROOT_USER # Prompt for username and password read -p "Enter new PostgreSQL username: " DB_USER # Check if username is provided if [[ -z "$DB_USER" ]]; then echo "Error: Username cannot be empty!" >&2 exit 1 fi # Check if user already exists in PostgreSQL if docker exec $CONTAINER_NAME psql -U $PGROOT_USER -tAc "SELECT 1 FROM pg_catalog.pg_roles WHERE rolname='$DB_USER'" | grep -q 1; then echo "Error: User '$DB_USER' already exists in PostgreSQL!" >&2 exit 1 fi echo "User '$DB_USER' does not exist. Proceeding..." read -s -p "Enter password for $DB_USER: " DB_PASS echo read -s -p "Confirm password for $DB_USER: " DB_PASS_CONFIRM echo # Check if passwords match if [ "$DB_PASS" != "$DB_PASS_CONFIRM" ]; then echo "Passwords do not match!" exit 1 fi # Create the user using docker exec and psql docker exec $CONTAINER_NAME psql -U $PGROOT_USER -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';" echo "User $DB_USER has been created successfully."