Search code examples
linuxbashshellubuntuunix

there is log echo and return echo in a function but it is returning only log echo only value instead of return cho


code :

function1(){

matchType=$1

if [[ $matchType == 'contains' ]];then
  PID=`pgrep -f  a`
elif [[ $matchType == 'exact' ]];then
  PID=`pgrep -x  a`
fi


if [[ $? -eq 0 ]];then
 echo "process id fetched successful"  // log echo
else
 echo"process id fetched failed"  // log echo
fi

echo "$PID"  //return echo

}


function2()
{
output=$(function1 contains)
}

value of output variable is 'process id fetched failed' instead of PID which I echoed at last in function 1

Requirement : it should return PID value to function2


Solution

  • Do you mean this?

    function1(){
    
    matchType=$1
    
    if [[ $matchType == 'contains' ]];then
      PID=`pgrep -f  a`
    elif [[ $matchType == 'exact' ]];then
      PID=`pgrep -x  a`
    fi
    
    
    if [[ $? -eq 0 ]];then
     echo "process id fetched successful" >&2 # this will set stdout fd to stderror
    else
     echo"process id fetched failed" >&2  # this will set stdout fd to stderror
    fi
    
    echo "$PID"
    
    }
    
    
    function2()
    {
    output=$(function1 contains)
    }
    

    or where do you want to log?