使用来自另一个 shell 脚本的返回代码函数 if 语句

问题描述 投票:0回答:1

我有

shell
名为
script_1.sh
的脚本,如下所示

# query
batch_count_query="SELECT COUNT(*) AS COUNT FROM ${db_name}.${table_name} WHERE BATCH_STATUS = "RUNNING";"

echo "************** $batch_count_query ******************************"

# Invoke the query
resp1=$(hive -e "$batch_count_query")


# return status check
if [ $? -eq 0 ]; then
    echo "******************* Command Ran Successfully ******************** "
    echo "Return message is ***************** ${resp1} ****************** "
else
    echo "******************* Error during the command execution ******************** "
    echo "Return message is ***************** ${resp1} ****************** "
    exit 1
fi

现在,每当查询失败时,脚本就会成功退出并显示错误消息。

现在我想对脚本做一些修改。我想在许多脚本中使用代码的

return status check
部分。 所以我尝试在
session_helper.sh
文件中创建一个函数,如下所示

# find return status of the command
command_exec_status ()
{
message=$1
if [ $? -eq 0 ]; then
    echo "******************* Command Ran Successfully ******************** "
    echo "Return message is ***************** ${message} ****************** "
else
    echo "******************* Error during the command execution ******************** "
    echo "Return message is ***************** ${message} ****************** "
    exit 1
fi
}

新的 shell 脚本

script_2.sh
如下:

source /home/$USER/session_helper.sh

# query
batch_count_query="SELECT COUNT(*) AS COUNT FROM ${db_name}.${table_name} WHERE BATCH_STATUS = "RUNNING";"

echo "************** $batch_count_query ******************************"

# Invoke the query
resp1=$(hive -e "$batch_count_query")   

# find status based on return code
command_exec_status $resp1

当我使用上面的新脚本时,即使查询失败。工作没有失败。

我在这里做错了什么。正确的方法是什么?

linux bash shell
1个回答
0
投票
source /home/$USER/session_helper.sh

# query
batch_count_query="SELECT COUNT(*) AS COUNT FROM ${db_name}.${table_name} WHERE BATCH_STATUS = "RUNNING";"

echo "************** $batch_count_query ******************************"

# Invoke the query
resp1=$(hive -e "$batch_count_query")   
ret=$?

# find status based on return code
command_exec_status $ret $resp1

还有

command_exec_status ()
{
if [ $1 -eq 0 ]; then
    echo "******************* Command Ran Successfully ******************** "
    echo "Return message is ***************** $2 ****************** "
else
    echo "******************* Error during the command execution ******************** "
    echo "Return message is ***************** $2 ****************** "
    exit 1
fi
}
© www.soinside.com 2019 - 2024. All rights reserved.