Tag: Scripting

Bash – How to return a value in a function

Here are some ways to return a value in a function in a Bash script:

1. Strings

function foo()
{
    echo "true"
}

retval=$(foo)

if [ "$retval" == "true" ];
then
     echo "true"
fi

2. Exit status

function foo()
{
    return 0
}

foo
retval=$?

if [ $retval == 0 ];
then
     echo "okay"
fi

3. Shared variable

retval=-1

function foo()
{
    retval=0
}

foo

if [ "$retval" == 0 ]
then
     echo "okay"
fi

Adapted from: http://stackoverflow.com/questions/8742783/returning-value-from-called-function-in-shell-script

Advertisements