24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

11.1.3. Positional parameters in functions<br />

Functions are like mini-scripts: they can accept parameters, they can use variables only known within the<br />

function (using the local shell built-in) and they can return values to the calling shell.<br />

A function also has a system for interpreting positional parameters. However, the positional parameters passed<br />

to a function are not the same as the ones passed to a command or script.<br />

When a function is executed, the arguments to the function become the positional parameters during its<br />

execution. The special parameter # that expands to the number of positional parameters is updated to reflect<br />

the change. Positional parameter 0 is unchanged. The <strong>Bash</strong> variable FUNCNAME is set to the name of the<br />

function, while it is executing.<br />

If the return built-in is executed in a function, the function completes and execution resumes with the next<br />

command after the function call. When a function completes, the values of the positional parameters and the<br />

special parameter # are restored to the values they had prior to the function's execution. If a numeric argument<br />

is given to return, that status is returned. A simple example:<br />

[lydia@cointreau ~/test] cat showparams.sh<br />

#!/bin/bash<br />

echo "This script demonstrates function arguments."<br />

echo<br />

echo "Positional parameter 1 for the script is $1."<br />

echo<br />

test ()<br />

{<br />

echo "Positional parameter 1 in the function is $1."<br />

RETURN_VALUE=$?<br />

echo "The exit code of this function is $RETURN_VALUE."<br />

}<br />

test other_param<br />

[lydia@cointreau ~/test] ./showparams.sh parameter1<br />

This script demonstrates function arguments.<br />

Positional parameter 1 for the script is parameter1.<br />

Positional parameter 1 in the function is other_param.<br />

The exit code of this function is 0.<br />

[lydia@cointreau ~/test]<br />

Note that the return value or exit code of the function is often storen in a variable, so that it can be probed at a<br />

later point. The init scripts on your system often use the technique of probing the RETVAL variable in a<br />

conditional test, like this one:<br />

if [ $RETVAL -eq 0 ]; then<br />

<br />

Or like this example from the /etc/init.d/amd script, where <strong>Bash</strong>'s optimization features are used:<br />

[ $RETVAL = 0 ] && touch /var/lock/subsys/amd<br />

Chapter 11. Functions 132

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!