Tuesday, November 17, 2009

Script to easily create a Postgres database

#! /bin/sh
if [ ${#} -ne 3 ]
then
 echo "Usage: $0 db_name username password"
 exit 2
fi

DBNAME=$1
USER=$2
PWD=$3

echo "
CREATE USER $USER WITH PASSWORD '$PWD';
CREATE DATABASE "$DBNAME"
    WITH OWNER "$USER"
    ENCODING 'UTF-8'
    LC_COLLATE = 'en_US.UTF-8'
    LC_CTYPE = 'en_US.UTF-8'
    TEMPLATE = "template0";
GRANT ALL PRIVILEGES ON DATABASE $DBNAME to $USER;
" | psql -U postgres -d template1

or if you want just to exec it once:
echo "
CREATE USER $USER WITH PASSWORD '$PWD';
CREATE DATABASE "$DBNAME"
    WITH OWNER "$USER"
    ENCODING 'UTF-8'
    LC_COLLATE = 'en_US.UTF-8'
    LC_CTYPE = 'en_US.UTF-8'
TEMPLATE = "template0"; GRANT ALL PRIVILEGES ON DATABASE $DBNAME to $USER; " | sudo -u postgres psql -U postgres -d template1

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.