Returning string values from a bash function

James Michael Fultz croooow at gmail.com
Sun Nov 22 07:52:31 UTC 2009


* Ray Parrish <crp at cmc.net> [2009-11-21 20:56 -0800]:
> I did some research, and wrote a little test script, and have discovered 
> one method of returning strings from functions. See code below -
> 
> #!/usr/bin/env bash
> #
> # This script is to test different methods of returning a string from a 
> function.
> #
> function ReturnString {
>      echo "Success!"
> }
> #
> Variable=`ReturnString`
> echo "Variable contains $Variable"
> exit
> 
> This worked great! Are there any other methods?

printf can be used more safely than echo when printing the value of
a variable since echo may try to interpret specific sequences as options
or escape sequences.

function ReturnString {
        retval="-n"
        # echo will interpret '-n' as an option
        echo "$retval"
        # printf prints the string as-is
        printf '%s\n' "$retval"
}

You can also set the value of a global variable to be checked after
a function execution.

# set to null value
ReturnValue=

function MakeMagicHappen {
        ReturnValue=xyzzy
}

MakeMagicHappen

if [[ "$ReturnValue" == "xyzzy" ]]; then
        : magic happens
fi




More information about the ubuntu-users mailing list