如何通过 .sh 文件添加 Postgres 扩展

How to add Postgres extensions via .sh file

我正在尝试通过编写以下脚本 (setup.sh) 为 Postgres 添加扩展:

sudo -u postgres psql my_database
CREATE EXTENSION adminpack;

当我执行 vagrant up 时,它应该 运行 并通过 运行 脚本自动添加扩展。但是,我收到

的错误消息
==> default: ERROR:  syntax error at or near "exit"
==> default: LINE 1: exit
==> default:         ^
==> default: /tmp/vagrant-shell: line 24: CREATE: command not found

请注意,我已经将所有必要的 postgres 安装到 运行 上面的代码中。此外,当我手动输入这些命令时,它成功创建了扩展。感谢提供帮助的人。

尝试:

sudo -u postgres psql my_database -c "CREATE EXTENSION adminpack"

https://www.postgresql.org/docs/current/static/app-psql.html

-c command

--command=command

Specifies that psql is to execute the given command string, command.

对于更复杂的脚本,也可以考虑使用 -f sql_file.sql,或者像这样:

psql <<EOF
\x
SELECT NOW();
SELECT * FROM foo;
EOF