I'm trying to execute SQK through psql under postgres account. I'm able run SQL that doesn't 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)
The problem appears with an SQL query that contains quotes like SELECT 'hi'. I'm testing with simple 'hi', but I would like to execute something like this from a 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 the command above
Some of my tests:
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\\'\''
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.