Organizing and reusing Bash code
Tutorials – Bash Functions
Learn how to make your Bash code more readable, robust, and reusable by managing the code within your Bash scripts.
A common problem with every scripting or programming language is that the more complex you make your code, the more difficult it is to understand, debug, and extend that code – unless you organize it correctly from the beginning.
In this installment of my shell scripting series, I show how Bash can help you organize your code correctly along with some related best practices. With a focus on how and why to use Bash functions and variable scopes, I'll present a shell script that can load code from other files, plus a few practical examples.
The Basics
Bash functions allow you to wrap up, as a single command, more or less complex chunks of code that perform any kind of task. You can then invoke these functions as many times as you like inside your script. Bash provides two equivalent syntaxes for defining functions. The first syntax consists of using the function
keyword, followed by the function name, and finally curly braces that enclose all the function's code:
[...]
Buy this article as PDF
(incl. VAT)