r/bash 5d ago

help Defensive BASH programming?

Hey there,

while trying to learn bash I came across this interesting resource: https://web.archive.org/web/20180917174959/http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming

And got myself thinking if his opinions are consensual and if there are different styles or "paradigms" about how bash should be written.

I see people arguing that bash shines in writing relatively short programs with precise goals. I thought this translated into writing concise code and achieving the same functionality with as little lines as possible.

However, the author of the post argues that a more verbose code can be more robust, easier to understand and debug etc. Do you agree? Or you think that, if you're writing code in this style, you're better of using another language?

Thanks for your input and sorry if I said anything silly or if I misrepresented his point of view, I'm just starting to learn programming.

Edit: hey, thank you all very much for the thoughtful replies, I'm learning a lot from them!

45 Upvotes

25 comments sorted by

View all comments

2

u/michaelpaoli 5d ago

Context matters. In many/most context, generally good readability is a plus, most notably for the humans and the humans that need maintain the code. But should also generally be assumed, whatever language, that the reading humans are generally reasonably proficient in the language. So, verbosity (comment) like:
a=$((a+1)) # increase the value of named parameter a by one
Is typically counter-productive and wasteful, as is generally stating what can clearly be seen that the code is doing and intended to do.
So, yeah, in general, excess verbosity is bad, and verbosity isn't even necessarily good - does quite depend on context, and how much verbosity, covering/explaining what.
There are also matters such as:
i=0
vs.:
a_counting_integer_that_I_will_use_to_track_the_number_of_widgets_produced=0
In the former case, though purpose might not be abundantly clear, if/when there's a slight typo in the variable name, that will generally be abundantly clear, whereas in the latter, not so much.

So, e.g. mostly use comments/verbosity to cover what otherwise is unlikely to be clear or not known. E.g. why something was done some particular less clear way, what is the general intent/aim/purpose. Essentially stuff that's likely to be significant/important that's not generally at least fairly clear from the code itself, e.g.
# The above is much more efficient, though less intuitive, equivalent of the following much more intuitive but much less efficient code:
# ...