如何用保留字转义“ su -c'psql ... -c \“ \”'“

时间:2019-06-19 10:27:40

标签: postgresql shell escaping psql quote

保留字'user'对我来说是个问题,因为它应该用“”(双引号)转义,但是要使用不同引号('和“以及\'和” /“)的组合,psql会将其作为用户传递(没有两次越狱)。如何使这个特殊单词逃脱?

我已经尝试过使用$$(美元报价的字符串常量)或将其放入不同的变量中,但没有任何帮助。

DB=mydb

MAIL_USER=my@mail.de
MAIL_PASS=password
MAIL_SERVER=mail.server.de
MAIL_PORT_IMAP=993
MAIL_PORT_SMTP=465

su -c "psql -d $DB -c \"INSERT INTO fetchmail_server(name, \"user\", type, server, port, is_ssl, password, active, priority, state, original) SELECT '$MAIL_USER', '$MAIL_USER', 'imap', '$MAIL_SERVER', $MAIL_PORT_IMAP, True, '$MAIL_PASS', True, 1, 'done', True WHERE NOT EXISTS (SELECT 1 FROM fetchmail_server WHERE name='$MAIL_USER')\"" postgres

预期结果是该命令在数据库中执行

INSERT INTO fetchmail_server(name, "user", type, server, port, is_ssl, password, active, priority, state, original) SELECT 'my@mail.de', 'my@mail.de', 'imap', 'mail.server.de', 993, True, 'password', True, 1, 'done', True WHERE NOT EXISTS (SELECT 1 FROM fetchmail_server WHERE name='my@mail.de')

1 个答案:

答案 0 :(得分:0)

谢谢@wildplasser,仅在与正确的用户一起使用psql的提示是正确的。因此,我能够减少一个嵌套级别。可行:

SQL_COMMAND='INSERT INTO fetchmail_server(name, "user", type, server, port, is_ssl, password, active, priority, state, "original") SELECT '\'$MAIL_USER\'', '\'$MAIL_USER\'', '\'imap\'', '\'$MAIL_SERVER\'', '\'$MAIL_PORT_IMAP\'', True, '\'$MAIL_PASS\'', True, 1, '\'done\'', True WHERE NOT EXISTS (SELECT 1 FROM fetchmail_server WHERE name='\'$MAIL_USER\'')'
echo $SQL_COMMAND
psql -d $DB -U postgres -c "$SQL_COMMAND"