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

0
0
Asked By MellowCedar47 On

I'm writing Bash functions to check whether a Docker network exists and create it only when necessary. In a language with Boolean return values, I would return true or false from a predicate such as is_existing_docker_network. In Bash, should a function return 0 when the network exists and 1 when it does not? Returning 1 feels like an error condition, so I'm unsure how these checks are conventionally written and used in if statements.

2 Answers

Answered By QuietHarbor8 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 should return 0 when its condition is true. For example, `docker_network_exists() { docker network inspect "$1" >/dev/null 2>&1; }` can be used directly with `if docker_network_exists "$name"; then ... fi`. A nonzero status does not necessarily mean something went wrong; it can simply mean the condition was false.

Answered By AmberPiano6 On

The important convention is that zero means success, not that zero universally means a conceptual true value. Shell conditionals check whether a command succeeded, so `if` treats exit status 0 as true. Use `return 1` or another nonzero value when a predicate is false, and reserve explicit error handling for operations such as a failed `docker network create`. For style, choose either `name()` or the `function name` form rather than combining both, and run the script through ShellCheck.

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.