Escaping single quotes in shell for postgresql

2019-07-18 22:40发布

问题:

Im trying execute sql through psql under postgres account. Im able run sql that doesnt contain quotes

root@server:/home/rosta/SCRIPTS# su postgres -c "psql -c 'SELECT NOW()'"
              now
-------------------------------
2014-06-07 09:38:17.120368+02
(1 row)

Problem appears with sql query that contains quotes like SELECT 'hi'. Im testing with simple 'hi', but I would like execute something like this from shell script.

su postgres -c "psql -c 'create database $DB_NAME template=template0 encoding='utf8' owner=aaa lc_collate='cs_CZ.utf8''"

Can anyone advise me how to escape quotes around encoding and collate in command above

Thanks

Rosta

Some of my test

root@server:/home/rosta/SCRIPTS# su postgres -c "psql -c 'SELECT \'hi\''"
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
root@server:/home/rosta/SCRIPTS# su postgres -c "psql -c 'SELECT \\'hi\\''"
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
root@server:/home/rosta/SCRIPTS# su postgres -c 'psql -c \'SELECT \\'hi\\'\''

回答1:

What I usually do is use double quotes (") for postgres -c's argument and escaped double quotes (\") for psql -c's argument. That way, I can use single quotes (') inside the SQL string with no problem:

[root@mycomputer ~]# su postgres -c "psql -c \"SELECT 'hi'  \" "
 ?column? 
----------
 hi
(1 row)


回答2:

Simplest way is to use a 'here document' , which ignores all quoting:

#!/bin/sh
DB_NAME=my_data_base

psql -U postgres postgres <<STOP_IT
create database $DB_NAME template=template0
  encoding='utf8'
  owner=aaa
  lc_collate='cs_CZ.utf8'
  ;
STOP_IT