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

Xia*_*lin 19 postgresql bash shell command

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

$ su - postgres -c 'psql -U postgres -d postgres'
# Alter user postgres with password 'password';
Run Code Online (Sandbox Code Playgroud)

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

su - postgres -c 'psql -U postgres -d postgres -c "alter user postgres with password ''password'';"'
Run Code Online (Sandbox Code Playgroud)

我听说使用双单引号来逃避单引号所以我添加了双引号'.但是显示错误消息:

ERROR:  syntax error at or near "password"
LINE 1: alter user postgres with password password;
Run Code Online (Sandbox Code Playgroud)

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

Cra*_*ger 43

如果您使用更容易sudo:

sudo -u postgres psql -U postgres -d postgres -c "alter user postgres with password 'password';"
Run Code Online (Sandbox Code Playgroud)

但也可以用su,这应该工作:

su - postgres -c "psql -U postgres -d postgres -c \"alter user postgres with password 'password';\""
Run Code Online (Sandbox Code Playgroud)

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

sudo更容易实现的原因之一是它使用更智能的方式执行子进程而不是运行第二个shell实例来执行此操作.你需要少一层shell元字符转义.