Using Functions: Parameters and Return Values

Problem

You want to use a function and you need to get some values into the function. How do you pass in parameters? How do you get values back?

Solution

You don’t put parentheses around the arguments like you might expect from some programming languages. Put any parameters for a bash function right after the function’s name, separated by whitespace, just like you were invoking any shell script or command. Don’t forget to quote them if necessary!

# define the function:
function max ()
{ ... }
#
# call the function:
#
max   128   $SIM
max  $VAR  $CNT

You have two ways to get values back from a function. You can assign values to variables inside the body of your function. Those variables will be global to the whole script unless they are explicitly declared local within the function:

# cookbook filename: func_max.1

# define the function:
function max ()
{
    local HIDN
    if [ $1 -gt $2 ]
    then
        BIGR=$1
    else
        BIGR=$2
    fi
    HIDN=5
}

For example:

# call the function:
max 128 $SIM
# use the result:
echo $BIGR

The other way is to use echo or printf to send output to standard output. Then you must invoke the function inside a $(), capturing the output and using the result, or it will be wasted on the screen:

# cookbook filename: func_max.2

# define the function:
function max ()
{
    if [ $1 -gt $2 ]
    then
        echo $1
    else
        echo $2
    fi
}

For example:

# call the function:
BIGR=$(max 128 $SIM)
# use the result
echo $BIGR

Discussion

Putting parameters on the invocation of the function ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.