Functions

Functions
A function can help you modularize your script.  In addition, the function is executed in the context of the same shell, no child process.  This will save on resources as you use functions.  Functions are a script within a script which can be defined by the user and stored in memory, allowing you to reuse the function repeatedly.  Arguments passed to the function are used as positional parameters within the function.

Lesson 6 | Lesson 8

Functions must be defined to be used and can be defined in two ways:


function functioname

{

shell commands

}


or


functname()

{

shell commands

}

The functions that are defined in the user login session may be viewed with the command:

declare -f

Functions do not run as separate processes as would happen if you ran a script and beware, if there is a function with the same name as a script the function will take precedence.

function work {
cd
echo “ Here is a list of your  files changed in the last 24 hours”
find  -mtime -1
}


In this function which is called “work”, when it is called by the name work all three commands will execute.

The purpose of the function is to bind the name of the function to the list of commands that you create.  This enables you to specifiy the name and all of the commands are executed.

function lsla { ls -la ; }

You can execute the list of commands by calling the name.

lsla

The function is defined in the script and then will be available by using the function name.  It will be available both to the shell and sub-shells that are started by the script.

Once you have defined a function in a script you can undefined it using the unset command.

unset functionname

Once it has been unset you will not be able to execute it.


Copyright CyberMontana Inc. and BeginLinux.com
All rights reserved. Cannot be reproduced without written permission. Box 1262 Trout Creek, MT 59874