Category Archives: Shell scripting

Return string from function – Bash scripting

How can we return string from a function ?

We can define a global variable and set the value in the function. This global variable can be accessed outside.

#!/bin/sh

# we created a global variable 
UPGRADE_PATH="abc"

#----------------------------------------------------------------------
# check if rpm package exists or not
#----------------------------------------------------------------------
function check_if_pkg_exist {
    PKG_NAME=$1
    echo "Checking if ${PKG_NAME} is exist"
    IS_EXIST=`rpm -qa | grep ${PKG_NAME}`
    if [[ ${IS_EXIST} =~ ${PKG_NAME}.* ]]; then
       return 1
    fi
    return 0
}


# function set the return value to global variable
function getUpgradePath {
    check_if_pkg_exist "chef-server"
    EXIST=$?

    if [[ ${EXIST} == 1 ]];then
        UPGRADE_PATH="chef"
    else
        UPGRADE_PATH="abc"
    fi

}

# we need to get upgrade path
# calling the function
getUpgradePath
echo "Upgrading from ${UPGRADE_PATH} to latest server"

String comparison in bash

Here is an example of comparing strings in bash. Also, uses logical AND operation.

ebscm_configure_status=0
MIGRATE_CHEF_DATA=""

# string comparison in bash
if [ $ebscm_configure_status == 0 ] && [ "${MIGRATE_CHEF_DATA}" != 'InProgress' ]; then
   echo "here"
fi