linux shell执行SQL查询



我试图在被记录到数据库后执行sql查询。虽然Postgres官方文档提到了选项c,但我总是得到错误,说命令,-c,——c不是有效的选项。

下面是我的shell脚本文件中的行。

psql "host='localhost' port=xxxx dbname='xxxxx' user='xxxx' password='xxxxx' -c='sql string'"

你混淆了长选项和短选项的语法…

:

#!/bin/sh
echo "Connect to DB"
psql "host='localhost' port=xxxx dbname='xxxxx' user='xxxx' password='xxxxx'" -c='select * from pg_stat_archive'

必须是:

#!/bin/sh
echo "Connect to DB"
psql "host='localhost' port=xxxx dbname='xxxxx' user='xxxx' password='xxxxx'" -c 'select * from pg_stat_archive'

等号仅用于长格式:--command=command

在shell脚本中使用here文档来避免-c

的终止和行为psql & lt; & lt; EOFx SELECT * FROM foo;EOF

查看具体的行为和示例https://www.postgresql.org/docs/12/app-psql.html

-c option必须放在前面,基于@Charles Duffy的评论

#!/bin/sh
echo "Connect to DB"
psql -c 'select * from any_table' "host='localhost' port=xxxx dbname='xxxxx' user='xxxx' password='xxxxx'"