我正在尝试通过 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/