1

I have the below three lines to be run in commandline using psql how can i do it.

CREATE DATABASE myproject;
CREATE USER myprojectuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

I just want to pass the sql strings as it is.

Santhosh
  • 9,965
  • 20
  • 103
  • 243
  • 2
    Put them into a file, then use `psql ... -f script.sql` –  Mar 19 '19 at 13:42
  • I am writing a script i want them to be visible – Santhosh Mar 19 '19 at 13:44
  • Possible duplicate of [How to execute multiple queries using psql command from bash shell?](https://stackoverflow.com/questions/28803651/how-to-execute-multiple-queries-using-psql-command-from-bash-shell) – Gregory Arenius Mar 19 '19 at 22:04

2 Answers2

5

As per the docs psql -c 'command;'

psql -c 'CREATE DATABASE myproject;' -c "CREATE USER myprojectuser WITH PASSWORD 'password';" -c 'GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;'
Scoots
  • 3,048
  • 2
  • 21
  • 33
2

As @horse suggested -f filename is a better option. You can also put them into a variable using a here document and execute it with the -c option .

read -r -d '' my_sqls << EOM
CREATE DATABASE myproject;
CREATE USER myprojectuser WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;
EOM
psql -c "$my_sqls"   # running all  the lines.
Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45
  • The temporary variable is just a complication; Bash trivially allows you to pass a multi-line string basically anywhere you can put a string which doesn't contain newlines. – tripleee Dec 09 '22 at 17:19