postgresql: run SQL commands using psql in commandline

后端 未结 2 961
-上瘾入骨i
-上瘾入骨i 2021-01-16 02:33

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 \'passwo         


        
相关标签:
2条回答
  • 2021-01-16 02:51

    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;'
    
    0 讨论(0)
  • 2021-01-16 03:12

    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.
    
    0 讨论(0)
提交回复
热议问题