How to get psql result in bash?
我正在尝试在bash中获取psql结果
1 2 3 | echo 'SELECT * FROM fictive_table LIMIT 1;' >> /tmp/x.sql psql --single-transaction -d dbname -f /tmp/x.sql echo $? |
这将失败,但是我在bash中得到的结果是0。逻辑/代码是否存在问题?
从手册
psql returns 0 to the shell if it finished normally, 1 if a fatal
error of its own (out of memory, file not found) occurs
更新:
@Andrea Spadaccini是正确的。这不是致命的。我怎样才能抓住它?
也许由查询触发的错误不是像手册中提到的那样致命的错误,即您没有用尽内存并且没有得到文件找不到错误。
进一步阅读手册,我读到:
psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own (out of memory, file not found) occurs, 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 变量;或者, - 更改方法,将查询输出保存到文件中,然后使用该文件。
使用选项
每个文档:
1 2 3 4 | -o filename --output=filename Put all query output into file filename. This is equivalent to the command \\o. |