What’s the idiomatic way to write Boolean-style functions in Bash?

0
0
Asked By MellowPine42 On

I'm writing Bash functions to check whether a Docker network exists and create it only when it doesn't. In a language with Boolean return values, I'd expect an `is_existing_docker_network` function to return true or false. In Bash, should the function return 0 when the network exists and 1 when it doesn't, even though a missing network isn't really an error? What's the usual pattern for this?

3 Answers

Answered By QuietMaple18 On

You don’t need explicit `return 0` statements when the last command already produces the desired status. For example:

`docker_network_exists() {
docker network inspect "$1" >/dev/null 2>&1
}`

The function returns 0 if inspection succeeds and a nonzero status otherwise. Callers can invert it with `if ! docker_network_exists "$network_name"; then ... fi`. Also, predicate names should describe a condition, such as `docker_network_exists`, rather than sounding like an action.

Answered By SilverKite63 On

The unintuitive part is that zero means success, and therefore acts like true in `if` conditions. Nonzero statuses mean false; `1` is conventional for a simple false result, although any nonzero value works. In your original function, the return values are backwards for its name: it returns success when the network is missing. Either rename it to something like `docker_network_missing`, or return 0 when the network is found and use `if ! docker_network_exists ...` when you want to create a missing network.

Answered By CedarFox7 On

Bash uses command exit statuses as Boolean values: status 0 means success/true, while any nonzero status means false or failure. So a predicate such as `docker_network_exists` should return the status of the inspection command directly: `docker_network_exists() { docker network inspect "$1" >/dev/null 2>&1; }`. Then use it naturally: `if docker_network_exists "$network_name"; then echo "already exists"; else docker network create "$network_name" || return 1; fi`. A nonexistent network isn’t necessarily an error for the overall workflow; it simply makes the test false.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.