在基于Linux / Unix的系统中,每当我们在shell中执行命令并回显$?
时,返回值在成功时为0,如果命令失败则返回值为1。
因此,如果我使用名为BCP的BULK COPY实用程序用于SQL Server,并且当源文件出错时命令失败。例如,如果我执行这样的bcp命令。
/opt/bin/bcp <tablename> in <source_file> -S -U -P -D
它说。 “ 0行复制”。这可能是由于源文件中的一些错误。然后,我做了echo $?
。返回的值仍为0.
当遇到错误时,有没有办法可以将返回值捕获为1?
感谢。
答案 0 :(得分:0)
BCP没有document任何返回值。这是一个缺点。您可以做的是将输出重定向到文件,并查找错误指示(可能是文本“错误”)。
答案 1 :(得分:0)
要在TT。的答案中添加更多细节,我将bcp输出写入另一个文件,然后通过它进行grep。我的代码看起来像...
/opt/mssql-tools/bin/bcp "$TABLENAME" in $f \
-S $DEST_IP \
-U $USER -P $PASSWORD \
-d $DEST_DB \
-c \
-t "\t" \
-e $EXPORT_STAGE/$TABLENAME/$TABLENAME.$(basename $f).bcperror.log \
| tee $EXPORT_STAGE/$TABLENAME/$TABLENAME.$(basename $f).bcprun.log
# note here that I preserve the bcp output to can later in script
# look for error messages in the bcp process run itself (manually done since bcp does not throw error codes)
echo -e "\n Checking for error messages in bcp output\n"
if grep -q "Error" $EXPORT_STAGE/$TABLENAME/$TABLENAME.$(basename $f).bcprun.log
then
echo -e "\n\nError: error message detected in bcp process output, exiting..."
exit 255
fi
# can delete since already printing to stdout as well (and can just log the whole thing)
rm -f $EXPORT_STAGE/$TABLENAME/$TABLENAME.$(basename $f).bcprun.log