我正在使用 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/