linuxbashshell

use return code function if statement from another shell script


I have shell script called script_1.sh like below

# 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

Now when ever the query fails the script is exiting successfully with error message.

Now I want to make some changes to the script. I want to use the return status check part of code in many scripts. So I tried to create a function in session_helper.sh file like below

# 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
}

New shell script script_2.sh is below:

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

when I use the above new script even though the query fails. The job is not failing.

What am I doing wrong here. What is the correct method.


Solution

  • 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
    

    And

    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
    }