简体   繁体   English

如何使用su -c和bash脚本引用psql语句?

[英]How to Quote a psql statement using su -c an a bash script?

I am trying the following statement in a bash script: 我正在bash脚本中尝试以下语句:

su -c  "psql -d myDB-c 'SELECT count(*) AS number, date_trunc('day'::text, users.registerdate) AS registerdate FROM users;'" postgres

The Problem is the 'day' parameter which needs to be quoted, but inside the quotes it doesn't work. 问题是需要引用的'day'参数,但是在引号内它不起作用。

You seem to be attempting to wrap single quotes inside single quotes, which of course you cannot do. 您似乎正在尝试将单引号包含在单引号中,这当然是您无法做到的。 'this'and'that' parses into 'this' followed by an unquoted and followed by 'that' , not into a quoted string this'and'that . 'this'and'that'解析为'this' ,然后一个不带引号and后跟'that' ,不进带引号的字符串this'and'that

The usual solution is to wrap single quotes in double quotes, or vice versa, so "this'and'that" or 'this"and"that' if substituting double quotes inside the quoted string is acceptable; 通常的解决方案是将单引号括在双引号中,反之亦然,因此'this"and"that'如果在双引号中替换双引号,则可以接受'this"and"that' "this'and'that"'this"and"that' but here, you already have both, so you can't do that (straightforwardly). 但是在这里,您已经拥有了两者,因此您不能(直接)做到这一点。

Assuming psql can read commands from stdin, the simple workaround here is to use a here document . 假设psql可以从stdin读取命令,那么这里的简单解决方法是使用here文档

su -c "psql -d myDB-c <<'____HERE' 
    SELECT count(*) AS number,
           date_trunc('day'::text, users.registerdate) AS registerdate
    FROM users;
____HERE" postgres

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM