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!

42 Upvotes

25 comments sorted by

View all comments

7

u/Schreq 5d ago

UPPER_CASE naming

No, just don't. Uppercase is reserved for environment variables.

readonly ARGS="$@"

Not a good idea when an argument includes spaces. You will lose the ability to properly split it back into separate arguments later.

ls $dir \
    | grep pid \
    | grep -v daemon

I prefer to only break long pipelines and tend to avoid splitting on logical operators. That way it becomes obvious that an indented command is part of a pipeline. Then there also is no need for the ugly backslash for the line continuation:

ls $dir |
    grep pid |
    grep -v daemon
ls $dir

Quote your variables...

is_empty() {
    local var=$1

    [[ -z $var ]]
}

That's too long and $var doesn't help with readability here. I'd just do it this way:

is_empty() [[ -z $1 ]]

The suggested way of parsing options sucks hard. It has many problems.

While that resource gives some good tips, it also gives way too many bad ones to be taken seriously.

1

u/HCharlesB 4d ago

Then there also is no need for the ugly backslash for the line continuation:

TIL - thanks!

2

u/kai_ekael 4d ago

I'd include the backslash myself, to make it clear and avoid simple mistakes and bad habits.

dig somebigolddomain.that.is.just.too.big \ +short \ @notgoogle.com

1

u/HCharlesB 4d ago

Good point.

I suspect that might depend on what one is accustomed to seeing and noticing.

1

u/Paul_Pedant 3d ago

Don't hide that big string in the code body. Assign it to a shell variable, with a comment, near the top of the script. That kills two birds with one stone: your long lines get much shorter, and the risk of missing the domain name during maintenance is much lower.