bash - 在 bash 脚本中读取从 psql 返回的错误

标签 bash postgresql psql

从 bash 脚本运行 psql 时,我需要检查错误。这是我们如何在脚本中运行的示例:

return_value=$(psql \
-X \
 $POSTGRES_CONNECTION_STRING \
-f ./build_table.sql \
-w \
-b \
-A \
-q \
-t \
)

psql_exit_status=$?

上面的语句工作正常除非在sql脚本中有一个错误,在这种情况下我在控制台上得到一些错误输出但是return_value设置为零,因为是 psql_exit_status

build_table sql 脚本创建一个表并从 csv 文件导入数据——如果 csv 文件中有错误,或者如果我故意拼错 create tableeeee 在 sql 脚本中,我在屏幕上看到 psql 错误,但据我所知,没有返回任何错误信息。

我试过在 psql 中使用 -o 标志输出到文件。没有显示,它是一个空白文件。我还尝试在 psql 语句后添加一个 2>&1 位,看看我是否可以通过这种方式获得一些错误信息,但没有任何作用。

我需要的是某种方式来告诉 sql 脚本异常退出和/或崩溃,而不必查看屏幕上的输出。我执行 psql 的方式可能吗?可能是我的一个 psql 标志出了问题?

最佳答案

来自psql documentation :

psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own occurs (e.g. out of memory, file not found), 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set.

因此您需要将 -v ON_ERROR_STOP=on 添加到您的 psql 选项。

但是设置这个变量有以下副作用:

By default, command processing continues after an error. When this variable is set to on, processing will instead stop immediately. In interactive mode, psql will return to the command prompt; otherwise, psql will exit, returning error code 3 to distinguish this case from fatal error conditions, which are reported using error code 1. In either case, any currently running scripts (the top-level script, if any, and any other scripts which it may have in invoked) will be terminated immediately. If the top-level command string contained multiple SQL commands, processing will stop with the current command.

关于bash - 在 bash 脚本中读取从 psql 返回的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944395/

相关文章:

bash - 删除 bash 中的双重扩展名

linux - 使用 Linux bash 脚本语言获取目录上的排序文件列表

javascript - 生成具有易于区分的类型/组的实体 ID

postgresql - 我如何解决这个问题来使用 psql? | psql : error: FATAL: role "postgres" does not exist

linux - 如何使用命令检查 Linux 中进程的 I/O 利用率

php - SED 命令 : won't insert the string I want

ruby-on-rails - 我如何重组这个大型 PostgreSQL 9.3 表,以便从 Rails 应用程序更有效地建立索引和搜索?

ruby-on-rails - 英雄数据库 :pull not working

openerp - OpernERP 删除具有依赖订单的合作伙伴

Java:连接到 psql 数据库会引发错误(ClassNotFoundException)