Shell Scripting – Functions

Shell Scripting – Functions

Shell Scripting – Functions. This is an introduction to functions in shell scripting. There are four main reasons to use functions:

  1. Re-usability – Easily reuse complex code
  2. Readability – The scripting is easier to follow. You can even use comments and descriptive function names
  3. Robustness
  4. Efficiency

Let’s look at two approaches to making a shell script:

Procedural Approach

  1. Setup new employee on Domain (Assign username/password, home directory, etc.)
  2. Setup new employee to group(s) (Assign user to groups)
  3. 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.

The basic syntax for a function in BASH Shell scripting is:

An example of this –

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.

shell scripting - functions in 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.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.



Updated on October 29, 2021

Pixelated Dwarf