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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s