代码之家  ›  专栏  ›  技术社区  ›  nmr

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

  •  0
  • nmr  · 技术社区  · 6 月前

    我有 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
    

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

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

    1 回复  |  直到 6 月前
        1
  •  2
  •   tink    6 月前
    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
    }