Easily find issues by searching: #<Issue ID>
Example: #1832
Easily find members by searching in: <username>, <first name> and <last name>.
Example: Search smith, will return results smith and adamsmith
Functions may process arguments passed to them and return an exit status to the script for further processing.
function_name $arg1 $arg2
The function refers to the passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
Example 24-2. Function Taking Parameters
#!/bin/bash # Functions and parameters DEFAULT=default # Default param value. func2 () { if [ -z "$1" ] # Is parameter #1 zero length? then echo "-Parameter #1 is zero length.-" # Or no parameter passed. else echo "-Param #1 is \"$1\".-" fi variable=${1-$DEFAULT} # What does echo "variable = $variable" #+ parameter substitution show? # --------------------------- # It distinguishes between #+ no param and a null param. if [ "$2" ] then echo "-Parameter #2 is \"$2\".-" fi return 0 } echo echo "Nothing passed." func2 # Called with no params echo echo "Zero-length parameter passed." func2 "" # Called with zero-length param echo echo "Null parameter passed." func2 "$uninitialized_param" # Called with uninitialized param echo echo "One parameter passed." func2 first # Called with one param echo echo "Two parameters passed." func2 first second # Called with two params echo echo "\"\" \"second\" passed." func2 "" second # Called with zero-length first parameter echo # and ASCII string as a second one. exit 0
The shift command works on arguments passed to functions (see Example 36-16).
But, what about command-line arguments passed to the script? Does a function see them? Well, let's clear up the confusion.
Example 24-3. Functions and command-line args passed to the script
#!/bin/bash # func-cmdlinearg.sh # Call this script with a command-line argument, #+ something like $0 arg1. func () { echo "$1" # Echoes first arg passed to the function. } # Does a command-line arg qualify? echo "First call to function: no arg passed." echo "See if command-line arg is seen." func # No! Command-line arg not seen. echo "============================================================" echo echo "Second call to function: command-line arg passed explicitly." func $1 # Now it's seen! exit 0
In contrast to certain other programming languages, shell scripts normally pass only value parameters to functions. Variable names (which are actually pointers), if passed as parameters to functions, will be treated as string literals. Functions interpret their arguments literally.
Indirect variable references (see Example 37-2) provide a clumsy sort of mechanism for passing variable pointers to functions.
Example 24-4. Passing an indirect reference to a function
#!/bin/bash # ind-func.sh: Passing an indirect reference to a function. echo_var () { echo "$1" } message=Hello Hello=Goodbye echo_var "$message" # Hello # Now, let's pass an indirect reference to the function. echo_var "${!message}" # Goodbye echo "-------------" # What happens if we change the contents of "hello" variable? Hello="Hello, again!" echo_var "$message" # Hello echo_var "${!message}" # Hello, again! exit 0
The next logical question is whether parameters can be dereferenced after being passed to a function.
Example 24-5. Dereferencing a parameter passed to a function
#!/bin/bash # dereference.sh # Dereferencing parameter passed to a function. # Script by Bruce W. Clare. dereference () { y=\$"$1" # Name of variable (not value!). echo $y # $Junk x=`eval "expr \"$y\" "` echo $1=$x eval "$1=\"Some Different Text \"" # Assign new value. } Junk="Some Text" echo $Junk "before" # Some Text before dereference Junk echo $Junk "after" # Some Different Text after exit 0
Example 24-6. Again, dereferencing a parameter passed to a function
#!/bin/bash # ref-params.sh: Dereferencing a parameter passed to a function. # (Complex Example) ITERATIONS=3 # How many times to get input. icount=1 my_read () { # Called with my_read varname, #+ outputs the previous value between brackets as the default value, #+ then asks for a new value. local local_var echo -n "Enter a value " eval 'echo -n "[$'$1'] "' # Previous value. # eval echo -n "[\$$1] " # Easier to understand, #+ but loses trailing space in user prompt. read local_var [ -n "$local_var" ] && eval $1=\$local_var # "And-list": if "local_var" then set "$1" to its value. } echo while [ "$icount" -le "$ITERATIONS" ] do my_read var echo "Entry #$icount = $var" let "icount += 1" echo done # Thanks to Stephane Chazelas for providing this instructive example. exit 0
Functions return a value, called an exit status. This is analogous to the exit status returned by a command. The exit status may be explicitly specified by a return statement, otherwise it is the exit status of the last command in the function (0 if successful, and a non-zero error code if not). This exit status may be used in the script by referencing it as $?. This mechanism effectively permits script functions to have a "return value" similar to C functions.
Terminates a function. A return command 1 optionally takes an integer argument, which is returned to the calling script as the "exit status" of the function, and this exit status is assigned to the variable $?.
Example 24-7. Maximum of two numbers
#!/bin/bash # max.sh: Maximum of two integers. E_PARAM_ERR=250 # If less than 2 params passed to function. EQUAL=251 # Return value if both params equal. # Error values out of range of any #+ params that might be fed to the function. max2 () # Returns larger of two numbers. { # Note: numbers compared must be less than 250. if [ -z "$2" ] then return $E_PARAM_ERR fi if [ "$1" -eq "$2" ] then return $EQUAL else if [ "$1" -gt "$2" ] then return $1 else return $2 fi fi } max2 33 34 return_val=$? if [ "$return_val" -eq $E_PARAM_ERR ] then echo "Need to pass two parameters to the function." elif [ "$return_val" -eq $EQUAL ] then echo "The two numbers are equal." else echo "The larger of the two numbers is $return_val." fi exit 0 # Exercise (easy): # --------------- # Convert this to an interactive script, #+ that is, have the script ask for input (two numbers).
For a function to return a string or array, use a dedicated variable.
count_lines_in_etc_passwd() { [[ -r /etc/passwd ]] && REPLY=$(echo $(wc -l < /etc/passwd)) # If /etc/passwd is readable, set REPLY to line count. # Returns both a parameter value and status information. # The 'echo' seems unnecessary, but . . . #+ it removes excess whitespace from the output. } if count_lines_in_etc_passwd then echo "There are $REPLY lines in /etc/passwd." else echo "Cannot count lines in /etc/passwd." fi # Thanks, S.C.
About AquaClusters Privacy Policy Support Version - 19.0.2-4 AquaFold, Inc Copyright © 2007-2017