psql返回值/错误终止了调用它的shell脚本吗? [英] psql return value / error killing the shell script that called it?
问题描述
我正在bash shell脚本中运行多个 psql
命令.其中一个命令将一个csv文件导入到表中.问题是,CSV文件偶尔会损坏,结尾处包含无效字符,并且导入失败.发生这种情况时,并且设置了 ON_ERROR_STOP = on
标志,我的整个shell脚本也将在该点停止.
I'm running several psql
commands inside a bash shell script. One of the commands imports a csv file to a table. The problem is, the CSV file is occasionally corrupt, it has invalid characters at the end and the import fails. When that happens, and I have the ON_ERROR_STOP=on
flag set, my entire shell script stops at that point as well.
以下是我的bash脚本的相关内容:
Here's the relevant bits of my bash script:
$(psql \
-X \
$POSTGRES_CONNECTION_STRING \
-w \
-b \
-L ./output.txt
-A \
-q \
--set ON_ERROR_STOP=on \
-t \
-c "\copy mytable(...) from '$input_file' csv HEADER"\
)
echo "import is done"
只要csv文件未损坏,上述方法都可以正常工作.如果是这样,psql会向控制台发出一条消息,该消息开始 ERROR:用于编码"UTF8"的字节序列无效:0xb1
,此时我的bash脚本显然停止了工作-我的上面的echo
语句不会执行,其他任何后续命令也不会执行.
The above works fine as long as the csv file isn't corrupt. If it is however, psql spits out a message to the console that begins ERROR: invalid byte sequence for encoding "UTF8": 0xb1
and my bash script apparently stops cold at that point-- my echo
statement above doesn't execute, and neither do any other subsequent commands.
根据psql文档,psql中的硬停止应该返回错误代码3:
Per the psql documentation, a hard stop in psql should return an error code of 3:
如果正常完成,psql将向外壳返回0,如果自身发生致命错误(例如,内存不足,找不到文件),则返回1,如果与服务器的连接断开并且会话未>,则返回2.交互式,如果脚本中发生错误并且设置了变量ON_ERROR_STOP,则为3
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
这很好,但是返回值3应该终止我的调用bash脚本吗?我可以防止这种情况吗?我想将 ON_ERROR_STOP
设置为 on
,因为如果初始导入成功,我实际上还有其他命令希望在该psql语句中运行,但如果成功,则不希望在该命令中运行没有.
That's fine and good, but is there a reason returning a value of 3 should terminate my calling bash script? And can I prevent that? I'd like to keep ON_ERROR_STOP
set to on
because I actually have other commands I'd like to run in that psql statement if the intial import succeeds, but not if it doesn't.
推荐答案
ON_ERROR_STOP
不能与 -c
选项一起使用.
ON_ERROR_STOP
will not work with the -c
option.
此外,在 psql
周围的 $(...)
看起来是错误的—您想将输出作为命令执行吗?
Also, the $(...)
surronding the psql
look wrong — do you want to execute the output as a command?
最后,您在 -L
选项之后忘记了反斜杠
Finally, you forgot a backslash after the -L
option
尝试使用此处的文档":
Try using a “here document”:
psql \
-X \
$POSTGRES_CONNECTION_STRING \
-w \
-b \
-L ./output.txt \
-A \
-q \
--set ON_ERROR_STOP=on \
-t <<EOF
\copy mytable(...) from '$input_file' csv HEADER
EOF
echo "import is done"
这篇关于psql返回值/错误终止了调用它的shell脚本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!