Escaping single quotes in shell for postgresql

匆匆过客 提交于 2019-12-11 03:05:25

问题


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


来源:https://stackoverflow.com/questions/24095203/escaping-single-quotes-in-shell-for-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!