Bash Scripting: Functions 2

Bash Scripting: Functions 2

Hi all. For this post I decided to share a scripting practice I’ve started using, utilising functions to help make the whole thing easier to read!

Looking back

This blog builds on my previous Bash Scripting series, including the first Functions blog, as well as using one of my more recent blogs as an example.

So what’s the big idea?

It’s a simple one really. Instead of writing a long script with lots of moving parts:
1) Define each relevant section as a function (using a nice, easy to understand name)
2) Call each section as needed in the main part of your script
For example:
I have these ten lines of code that inject the device’s hostname into a configuration profile.
Rather then add them into the script body, I have defined them as the function “InjectFQHostname”. Then, later in the actual script section, I call this by it’s nice and human-friendly name, with an added comment to sum up the task those few lines are carrying out.

But, why?

Short answer? It makes the code cleaner and easier to read.
Long answer? Even with heavy commenting on each line, it can be difficult to follow the script and understand what it is trying to do.
This sort of verbose commenting can also both bloat and distorted the look of the script, and actually be counter-intutuive and more confusing to follow.
By turning most items into functions, I can give each block of code that performs a single task, or collection of closely related tasks, an easy to understand name, and a one line comment explaining what its up to.
A secondary reason is to have the ability to reuse code. An example from this script is the “writelog” function, defined here. This allows me to use this 5-line function in multiple places, using repetition and reducing the risk of ‘overcrowding’ the script, again making it harder to read.

But couldn’t you solve most of these issues by not commenting the code?

I’ll let you in on a secret. Always comment your code.
Who knows when your pretty looking script breaks and you have to fix it.
Could be tomorrow, could be in 5 years time!
Can you remember exactly which sections of code did what? What if its a colleague, or indeed a replacement, that has to work on it?
Commenting allows you to leave notes or documentation, both of the script as a whole, and each section you deem relevant.


And that’s it for now, hopefully this extra view of functions will give you other ideas on using it in your scripts. Feel free to share your examples in the comments below.