Functions provide a method of grouping frequently used (sets of) commands together using an easily referenced user defined name. This allows pieces of code to be grouped in a more logical way, that can be called upon or repeated, as required.


Created by placing parentheses after the function name, or by use of the function keyword followed by the function name:


function_name () {




function function_name {




Either of the above is valid, but unlike other programming languages the parentheses can not be used to pass arguments into the function.


To use a function, simply specifying the function name:


Arguments can be passed into a function in a similar method as passing in from the command line:


Numerical values can be returned from the function by using the keyword return and then specifying the numerical value to be returned, which can then be accessed via use of the special variable $?

*Typically a return status of 0 indicates that everything went successfully. A non zero value indicates an error occurred.


Command substitution can be used to return the result of a calculation:

The target file is passed in as an argument when running the script:

  • targetFile.txt

The result is that the passed in file is used as the argument when the function is called and its returned value is assigned to the calling variable, ultimately counting and echoing the number of lines in the file.