postgresql 在 unix shell 脚本中检查 psql 命令的返回状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37072245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check return status of psql command in unix shell scripting
提问by Naveen Reddy CH
I am using psql command to connect and issue a query on postgreSQL database. Can anybody let me know how to check the return status of the executed query in shell script.
我正在使用 psql 命令连接并在 postgreSQL 数据库上发出查询。任何人都可以让我知道如何在 shell 脚本中检查已执行查询的返回状态。
I have used echo $?
command to check the status but it always returning zero.
我已经使用echo $?
命令来检查状态,但它总是返回零。
Thanks for the help.
谢谢您的帮助。
回答by Daniel Vérité
psql
return code is documented as:
psql
返回代码记录为:
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.
退出状态 如果
psql 正常完成,则返回 0 到 shell,如果发生自身的致命错误(例如内存不足,找不到文件),则返回 1,如果与服务器的连接出现故障并且会话没有交互,则返回 2,以及3 如果脚本中发生错误并且设置了变量 ON_ERROR_STOP。
You probably just want to use ON_ERROR_STOP.
您可能只想使用 ON_ERROR_STOP。
Failure getting tested and reported to the shell:
测试失败并报告给 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
Failure getting ignored and not reported to the shell:
失败被忽略并且没有报告给 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