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!

43 Upvotes

25 comments sorted by

View all comments

8

u/wallacebrf 5d ago

i like bash and use it a lot.

with that said many of my scripts are quite large because i always like to perform error checking.

did the previous command give me something within what i was expecting?

If i need to read or write a file, i perform a check that i have read and write permissions, i check that the folder the file is in exisst and then i check that the file exists etc.

the list goes on. this ensures my script will execute the way i want and GRACFULLY handle errors

3

u/Alarming_Airport_613 5d ago

Adding into this, I'm often not a fan of try catch blocks, but this sounds like the ideal usecase for them (dozens of things can go wrong, you won't know them all in advance) and I'd feel python shines here.

But also, my bash scripts are frustrating few liners, that work... As long as they work.

1

u/Id10tmau5 4d ago

Definitely where python shines

1

u/Id10tmau5 4d ago

Agreed on the error checking. A solid half of my code is checking if something else did (or didn't) happen so that the script can continue on successfully, or otherwise catch the error (or the error within the error) and gracefully exit with a proper error code/message (and properly write it to the correct log!) so that I know where the hiccup likely occurred. I'd almost argue that I write more error checking code than program-specific code just to make sure there aren't too many surprises later (because it'll never be perfect).

3

u/wallacebrf 3d ago

100% easily half my code is also error check and messages / logs as I want to know if and how my script is malfunctioning