0

This is what I am doing manually.

user@host: sudo -u postgres psql
postgres=# create database myproj;
postgres=# create user myuser with password 'mypass';
postgres=# alter role myuser set client_encoding to 'utf8';
postgres=# alter role myuser set default_transaction_isolation to 'read committed';
postgres=# alter role myuser set timezone to 'UTC';
postgres=# grant all privileges on database myproj to myuser;
postgres=# \q

The question is if I want to save it to .sh file and run, what should be the content. something like this?

sudo -u postgres psql -c "create database myproj;"
sudo -u postgres psql -c "create user myuser with password 'mypass';"
sudo -u postgres psql -c "alter role myuser set client_encoding to 'utf8';"
sudo -u postgres psql -c "alter role myuser set default_transaction_isolation to 'read committed';"
sudo -u postgres psql -c "alter role myuser set timezone to 'UTC';"
sudo -u postgres psql -c "grant all privileges on database myproj to myuser;"

1 Answer 1

1

You may use a Here document

$cat yourscript.sh
sudo -u postgres psql <<'INP'
create database myproj;
create user myuser with password 'mypass';
..
..
INP

If you wish to isolate the SQL commands from shell, put it in a separate .sql file and call using -f option or psql \i option.

$cat dbscript.sql
     create database myproj;
     create user myuser with password 'mypass';
..

Run it as

sudo -u postgres psql -U <yourusername> -d <yourdbname> -f dbscript.sql

Or

sudo -u postgres psql <<INP
\i /path/dbscript.sql
Sign up to request clarification or add additional context in comments.

4 Comments

I can not save sql file so I am trying first approach. I have prepared the .sh file at pastebin. If possible can you please check if I understood your answer correctly?
The first and last cd commands are just to understand that this is part of large .sh file. Is this ok?
@Rahul : The cd command's not needed. Rest seems Ok. Please verify it in your test environment before running.
cd commands are there to confirm that this is part of larger .sh file and can work that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.