用于更改 postgresql 用户密码的 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16049399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:36:33  来源:igfitidea点击:

a bash script to change postgresql user password

bashpostgresqlshellcommand

提问by Xianlin

I can change the postgresql user password in this way (2 steps):

我可以通过这种方式更改 postgresql 用户密码(2 个步骤):

$ su - postgres -c 'psql -U postgres -d postgres'
# Alter user postgres with password 'password';

Now I want to use a single line command (1 step) to change the password such as:

现在我想使用单行命令(1 步)来更改密码,例如:

su - postgres -c 'psql -U postgres -d postgres -c "alter user postgres with password ''password'';"'

I heard using double single quote to escape one single quote so I added double quote '. However is shows error message:

我听说使用双单引号来转义单引号,所以我添加了双引号'。但是显示错误消息:

ERROR:  syntax error at or near "password"
LINE 1: alter user postgres with password password;

Could someone let me know how to use one line of command to do this?

有人可以让我知道如何使用一行命令来做到这一点吗?

回答by Craig Ringer

Easier if you use sudo:

如果您使用更容易sudo

sudo -u postgres psql -U postgres -d postgres -c "alter user postgres with password 'password';"

but it's possible with su too, this should work:

但是 su 也可以,这应该有效:

su - postgres -c "psql -U postgres -d postgres -c \"alter user postgres with password 'password';\""

I've used outer double quotes and escaped the inner double quotes so they pass through as part of a single call argument to suand get unescaped by the shell so the actual query text gets passed as a single arg to psql including the single-quoted password.

我使用了外部双引号并转义了内部双引号,因此它们作为单个调用参数的一部分传递给su并被 shell 取消转义,因此实际查询文本作为单个 arg 传递给 psql,包括单引号密码.

One of the reasons sudo is easier for this is that it uses a smarter way of executing the subprocess instead of running a second shell instance to do it. You need one less layer of shell metacharacter escaping.

sudo 更容易做到这一点的原因之一是它使用一种更智能的方式来执行子进程,而不是运行第二个 shell 实例来执行它。您需要少一层 shell 元字符转义。