简体   繁体   English

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

[英]Check return status of psql command in unix shell scripting

I am using psql command to connect and issue a query on postgreSQL database. 我使用psql命令连接并在postgreSQL数据库上发出查询。 Can anybody let me know how to check the return status of the executed query in shell script. 任何人都可以告诉我如何在shell脚本中检查已执行查询的返回状态。

I have used echo $? 我用过echo $? command to check the status but it always returning zero. 命令检查状态,但它总是返回零。

Thanks for the help. 谢谢您的帮助。

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 (eg 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,如果发生自身致命错误则返回1(例如内存不足,文件未找到),2如果与服务器的连接变坏且会话不是交互式,则返回2脚本中发生错误,并且设置了变量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

如前所述在这里 ,你还可以在你的SQL文件/脚本的顶部添加此行:

\set ON_ERROR_STOP true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM