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.
3 Answers
You can simplify the workflow by letting the check command provide the status and only explicitly return a failure status when creation fails: `docker_network_exists() { docker network inspect "$1" >/dev/null 2>&1; }` followed by `if docker_network_exists "$network_name"; then log_warn "network already exists"; else docker network create "$network_name" || { log_error "network creation failed"; return 1; }; fi`. Successful functions often need no explicit `return 0`, because they inherit the status of their final successful command. Also, use a name like `docker_network_exists` so the function reads naturally as a predicate.
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.
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
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically