Shell Scripting – Functions
Shell Scripting – Functions. This is an introduction to functions in shell scripting. There are four main reasons to use functions:
- Re-usability – Easily reuse complex code
- Readability – The scripting is easier to follow. You can even use comments and descriptive function names
- Robustness
- Efficiency
Let’s look at two approaches to making a shell script:
Procedural Approach
- Setup new employee on Domain (Assign username/password, home directory, etc.)
- Setup new employee to group(s) (Assign user to groups)
- Announce new employee to colleagues (code that send out email, push update to company directory, etc.)
Functional Approach
setup_domain_for $new_employee_name
assign_to_groups $new_employee_name
team_announce_for $new_employee_name
You can use a functions file to bring in the most commonly used functions that are used.
#! /bin/bash# main script header
VARIABLES_FILE=’/home/user/scripts/common_variables.sh’
FUNCTIONS_FILE=’/home/user/scripts/common_functions.sh’
source $VARIABLES_FILE
source $FUNCTIONS_FILE
# functions call starts here
The basic syntax for a function in BASH Shell scripting is:
function descriptive_name {
# code for the function goes here
}
An example of this –
function today()
{
TODAY= date +%A
}
It is “called” by naming the function that it came from and the variable that we want:
today
$TODAY
This gives us the day of the week. Here is what our output looks like for our greeting script.
Conclusion
I know that this barely scratches the surface of functions in BASH shell scripting. BASH functions are powerful and flexible. There are articles that say that you should “always” put things into functions. I think that there are times when you can put in what you need to get the job done. Combining functions with IF statements and Case statements will give you a lot of flexibility.
Here is our functions greeting script all zipped up for you. I put everything into functions just to show you how it looks.
Take a look at the Bash3 Boilerplate project code for much more information on scripting. This includes lots of information on shell scripting and functions.