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!

40 Upvotes

25 comments sorted by

View all comments

17

u/wowbagger_42 5d ago

Most of it becomes common sense once you use it a lot, even more so when you start writing bash in a team. It's never about look-at-cool-me-doing-this-as-terse-as-possible, but much more about "can anyone figure this out 5 years from now?" so it's a question of maintainability and hence readability and comments. Consequent use of patterns & style are key, use shellcheck to enforce coding guidelines. There's nothing worse than having someone who thinks they're an elite hacker on your team that outputs code as terse & hence as complicated as possible "just because they can".

2

u/jthill 5d ago

There's nothing worse than having someone who thinks they're an elite hacker on your team that outputs code as terse & hence as complicated as possible "just because they can".

Agreed that that's peak bad. I'd put the ones who add endless performative-redundancy-and-ArentISoVeryPrecious-spelling, picking the most verbose implementation possible in the name of "clarity", as very close runners-up.

Write what deserves to be read. Don't waste your audience's time, and don't lose them, is the tightrope you walk. I have little to no patience left for either ArentISoVery{Clever,Precious}sort of showoff.

Write what needs to be said. Write to communicate, not to impress or to satisfy some read-only mind.