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

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

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

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

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

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

有人能告诉我如何使用一行命令来做这件事吗?

推荐答案

如果你使用sudo:

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

但su也有可能做到这一点:

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

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

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

Postgresql相关问答推荐

此PostgreSQL汇总分组不适用于窗口表达式

PostgreSQL plpgsql函数问题

我可以将jsonb_set与来自SELECT语句的新值(第三个参数)一起使用吗?

PL/pgSQL中的IP递增函数

返回行值和行计数的总和

合并两个字典并创建一个包含更新凭据的字典列表

Postgres中的GROUP BY - JSON数据类型不相等?

从time without time zone和时区名称中获取time with time zone

在 PostgreSQL 中显示正在运行的查询的全文

使用 current_setting() 判断值

使用 pg_dump 和 psql -U postgres db_name < ... 移动数据库会导致ERROR: relation "table_name" does not exist

从 PostgreSQL 序列中 Select 多个 id

为 postgresql 存储过程设置隔离级别

获取 psycopg2 count(*) 结果数

PGError:错误: column of relation does not exist

如何从 CSV 为 PostgreSQL 副本生成模式

错误:关系列不存在 PostgreSQL,无法运行插入查询

使用 Postgresql 在过滤器中制作 Sqlalchemy 使用日期

使用 Postgresql 数据库(OSX Lion)创建 Rails 3.1 应用程序

在 Postgres 9.0+ 中使用 PL/pgSQL 在表上循环