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\\'\''
What I usually do is use double quotes (
"
) forpostgres -c
's argument and escaped double quotes (\"
) forpsql -c
's argument. That way, I can use single quotes ('
) inside the SQL string with no problem:Simplest way is to use a 'here document' , which ignores all quoting: