我有一个简单的bash脚本,后面有bteq;
bteq <<EOF!
.set width 255
.set format off
.set titledashes off
.logon ${HOST}/${USER}, ${PASSWORD};
.export report file=test_file.rpt;
SELECT count(*) from test_db.test_table; /*this table contains 90 rows in my case*/
.IF ERRORCODE <> 0 THEN .EXIT ERRORCODE;
.IF ACTIVITYCOUNT = 0 THEN .GOTO ALLOK
.LOGOFF;
.EXIT 3;
.LABEL ALLOK;
.LOGOFF;
.EXIT 0;
EOF!
/*Now if the above bteq returns 0,(i.e. RET_FLAG = 0) the below code executes
with RC (return code) = 0 but if it returns values other than 0 below code doesn't executes and finally bash exits.*/
RET_FLAG=$?
print_msg "RET_FLAG: $RET_FLAG " /*when return code other than 0 this line is not printed*/
if [ $? -gt 0 ];
then
print_msg "Hello world get succeed" /* printing function */
exit 1
fi
我整天都在努力弄明白,但仍然没有进步。任何人的帮助都会挽救我的夜晚。谢谢。
答案 0 :(得分:0)
在if条件下,请使用RET_FLAG -gt 0.而不是$?
答案 1 :(得分:0)
好的,我发布了问题,我找到了答案:)
实际上问题是从 bteq 到bash的退出代码
对于任何子程序调用,bash行为,Bash通常会在收到0以外的退出代码时退出。
有关bash http://bencane.com/2014/09/02/understanding-exit-codes-and-how-to-use-them-in-bash-scripts/中退出代码的更多详细信息
现在让我们看看上面的问题,让我们试着回答它,
bteq <<EOF!
.set width 255
.set format off
.set titledashes off
.logon ${HOST}/${USER}, ${PASSWORD};
.export report file=test_file.rpt;
#Assumption:- below query executes successfully
SELECT count(*) from test_db.test_table; /*this table contains 90 rows in my case*/
.IF ERRORCODE <> 0 THEN .EXIT ERRORCODE;
.IF ACTIVITYCOUNT = 0 THEN .GOTO ALLOK
#since ACTIVITYCOUNT will be other than 0(for above assumption to be true), code will execute exactly the line below
#thus bteq will exit with exit status 3
.LOGOFF;
.EXIT 3;
.LABEL ALLOK;
.LOGOFF;
.EXIT 0;
EOF!
现在,如果上面的bteq返回0,(即RET_FLAG = 0
),则执行下面的代码
使用RC (return code) = 0
,因为bash将退出代码0视为成功
如果它返回的值不是0,则代码不会执行并最终执行bash退出,因为bash会将0以外的退出代码视为错误。
&#34; 退出放弃当前的shell &#34; -somewhere from stackoverflow
RET_FLAG=$?
print_msg "RET_FLAG: $RET_FLAG " /*when return code other than 0 this line is not printed*/
if [ $RET_FLAG -gt 0 ]; #previously I was using if[$ -gt 0]
then
print_msg "Hello world get succeed" /* printing function */
exit 1
fi
如果从子程序调用或bteq中使用0以外的退出代码处理此类不需要的退出,我们可以做些什么?
Sol: - 我们可以在bteq的最后阶段使用set +e
,set +e
即使退出代码不是0,也会停止bash退出,但不建议使用此方法。
最佳做法是使用trap
,请参阅以下文档,了解如何在bash中使用陷阱
http://linuxcommand.org/wss0160.php
http://www.gnu.org/software/bash/manual/bash.html