如何在bash脚本执行的psql命令中正确使用\c等元命令?
报错原因
你遇到的语法报错是因为psql的-c参数仅支持传入纯SQL语句,而\c、\i属于psql客户端专属的元命令,不会被服务端识别,直接和SQL语句混写传入会被服务端当成非法SQL语法抛出错误。
方案1:拆分两条psql命令执行(更简洁)
直接拆分步骤,用psql自带参数替代元命令,不需要处理转义问题:
# 1. 新建数据库 psql -U postgres -h localhost -p 5433 -c "create database test_database;" # 2. 直接连接新库执行SQL文件,-d指定目标库,-f指定要执行的文件 psql -U postgres -h localhost -p 5433 -d test_database -f integration-test/src/test/resources/init.sql
方案2:使用Here Document实现多步操作(和手动执行逻辑完全一致)
如果后续有更多混合SQL和元命令的操作,可以用here-doc的方式把所有操作批量传给psql客户端处理:
psql -U postgres -h localhost -p 5433 << EOF create database test_database; \c test_database \i integration-test/src/test/resources/init.sql EOF
可选优化
可以给psql命令增加-v ON_ERROR_STOP=1参数,执行过程中一旦遇到错误就立即终止,避免后续无效操作,方便排查问题,示例:
psql -v ON_ERROR_STOP=1 -U postgres -h localhost -p 5433 -d test_database -f integration-test/src/test/resources/init.sql
内容的提问来源于stack exchange,提问作者Teresa
相关产品推荐
相关产品推荐

