linux - 在 postgresql 的 shell 中转义单引号

标签 linux postgresql shell escaping psql

我正在尝试通过 postgres 帐户下的 psql 执行 SQK。我可以运行 SQL 不包含引号

root@server:/home/rosta/SCRIPTS# su postgres -c "psql -c 'SELECT NOW()'"
              now
-------------------------------
2014-06-07 09:38:17.120368+02
(1 row)

问题出现在包含 SELECT 'hi' 等引号的 SQL 查询中。我正在使用简单的“hi”进行测试,但我想从 shell 脚本执行类似这样的操作。

su postgres -c "psql -c 'create database $DB_NAME template=template0 encoding='utf8' owner=aaa lc_collate='cs_CZ.utf8''"

谁能告诉我如何在上面的命令中绕过编码和整理引号

我的一些测试:

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\\'\''

最佳答案

我通常做的是为 postgres -c 的参数使用双引号 (") 和转义双引号 (\")对于 psql -c 的参数。这样,我就可以毫无问题地在 SQL 字符串中使用单引号 ('):

[root@mycomputer ~]# su postgres -c "psql -c \"SELECT 'hi'  \" "
 ?column? 
----------
 hi
(1 row)

关于linux - 在 postgresql 的 shell 中转义单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24095203/

相关文章:

postgresql - 在 Postgres 中使用 floor() 从大表中高效地进行选择

linux - 使用 perl 的过程控制和并发程序

linux - vim ./test.py 和 test.py 之间的区别

Linux脚本变量到SCP并删除文件

linux - 在 linux 上链接共享库时,是否包含所有模块?

c - 僵尸,gdb 无法附加,如何检查上次调用或回溯

postgresql - 如何从 postgresql 函数或触发器发送一些 http 请求

sql - 从自连接中获取唯一对,加上没有匹配的行

linux - 如何根据 linux 中的相邻列值获取列值?

linux - 在 Linux 系统上保留大页面