Escaping single quotes in shell for postgresql

前端 未结 2 1900
青春惊慌失措
青春惊慌失措 2021-01-22 17:41

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 &qu         


        
相关标签:
2条回答
  • 2021-01-22 18:37

    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
    
    0 讨论(0)
  • 2021-01-22 18:42

    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)
    
    0 讨论(0)
提交回复
热议问题