Promoting Script Readability

Problem

You’d like to make your script as readable as possible for ease of understanding and future maintenance.

Solution

  • Document your script as noted in Documenting Your Script and Embedding Documentation in Shell Scripts

  • Indent and use vertical whitespace wisely

  • Use meaningful variable names

  • Use functions, and give them meaningful names

  • Break lines at meaningful places at less than 76 characters or so

  • Put the most meaningful bits to the left

Discussion

Document your intent, not the trivial details of the code. If you follow the rest of the points, the code should be pretty clear. Write reminders, provide sample data layouts or headers, and make a note of all the details that are in your head now, as you write the code. But document the code itself too if it is subtle or obscure.

We recommend indenting using four spaces per level, with no tabs and especially no mixed tabs. There are many reasons for this, though it often is a matter of personal preference or company standards. After all, four spaces is always four spaces, no matter how your editor (excepting proportional fonts) or printer is set. Four spaces is big enough to be easily visible as you glance across the script but small enough that you can have several levels of indenting without running the lines off the right side of your screen or printed page. We also suggest indenting continued lines with two additional spaces, or as needed, to make the code the most clear.

Use vertical white space, with separators ...

Get bash Cookbook 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.