postgresql - 检查 unix shell 脚本中 psql 命令的返回状态

标签 postgresql shell

我正在使用 psql 命令连接 postgreSQL 数据库并发出查询。谁能告诉我如何在 shell 脚本中检查已执行查询的返回状态。

我已经使用 echo $? 命令来检查状态,但它总是返回零。

感谢您的帮助。

最佳答案

psql 返回码 is documented as :

EXIT STATUS
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.

您可能只想使用 ON_ERROR_STOP。

测试失败并报告给 shell:

$ psql -d test -v "ON_ERROR_STOP=1" <<EOF
select error;
select 'OK';
EOF

ERROR:  column "error" does not exist
LINE 1: select error;

$ echo $?
3

失败被忽略且未报告给 shell:

$ psql -d test  <<EOF
select error;
select 'OK';
EOF
ERROR:  column "error" does not exist
LINE 1: select error;
               ^
 ?column? 
----------
 OK
(1 row)

$ echo $?
0

关于postgresql - 检查 unix shell 脚本中 psql 命令的返回状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37072245/

相关文章:

数据库实现帮助: Time-Series data

sql - 如何在同一列中加入不同的 FK 值?

linux - 如何强行删除数据文件夹以及部分postgres9.1卸载脚本

python - 运行 'conda init'后关闭并重启shell

postgreSQL 数据库全局唯一业务键

postgresql - 在符号之间搜索文本

linux - 如何在 *nix 上查找/grep 目录名称匹配 "x"但不匹配 "y"的所有路径?

linux - 识别长时间运行进程的 PID

linux - shell 脚本由 crontab 运行但没有输出

sql - 我无法弄清楚 v_out 和 v_in 在 SQL 语句中的含义