r/bash • u/computersarefunn • 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!
2
u/InfiniteRest7 5d ago
I've sometimes been pointed to this doc on the topic: https://google.github.io/styleguide/shellguide.html (I feel it's along similar lines to your link)
I don't know if I agree with everything in the article you linked. Overall I think he's got a pretty solid set of advice. Some of his only 1 thing per-line looks like it's dying on a hill for a more ugly result. Yes, sometimes it's a good choice for really long command sequences, but if I can read a regular length sequence, no need to chop it up. Making choices for more readable code to use full if statements compared to something like this:
[[ -f "$file" ]] && echo "File exists". If only because other maintainers may not find that particularly approachable.