2

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.

3
  • 3
    Put them into a file, then use psql ... -f script.sql Commented Mar 19, 2019 at 13:42
  • I am writing a script i want them to be visible Commented Mar 19, 2019 at 13:44
  • Possible duplicate of How to execute multiple queries using psql command from bash shell? Commented Mar 19, 2019 at 22:04

2 Answers 2

6

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;'
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.