Chapter 11. Shell Scripting

For the majority of this book, we’ve looked at the various elements that make up bash and how you can use them in writing shell scripts. If you’ve used other programming languages you will know that there is a difference between writing a piece of code that gets a job done and writing a piece of code that does the job but is also maintainable and conforms to what we could call “good practice.”

This chapter will give a brief introduction to some aspects of good practice and writing maintainable shell scripts along with helpful tips and tricks that you can use to make writing scripts easier.

What’s That Do?

Six months ago you coded up a 100 line shell script. It made perfect sense then, but now you look at it and wonder, “Just what does that do?” This is a common pitfall among programmers—especially those writing in a shell language. Unfortunately, shells have developed with more than their fair share of obscure punctuation. This is a blessing for keeping typing to a minimum but doesn’t help readability. It’s important to make your code as readable as possible.

Comments

The first rule of shell scripting is to comment your code. You should do this right from the start, even if the script is only a couple of lines long. Shell scripts have a habit of growing from a couple of lines to many hundreds of lines as more features are added, so it’s best to get into the habit of commenting your code right at the beginning.

To start with, consider having a main header or ...

Get Learning the bash Shell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.