Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single quotes in shell for postgresql

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\\'\''
like image 556
user3717337 Avatar asked Aug 10 '26 13:08

user3717337


2 Answers

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)
like image 196
Mureinik Avatar answered Aug 13 '26 03:08

Mureinik


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
like image 26
wildplasser Avatar answered Aug 13 '26 05:08

wildplasser