Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
post: bash boolean string statements
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
collections/_posts/2022-02-08-parsing-boolean-string-statements-in-bash.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
--- | ||
layout: post | ||
title: "Parsing boolean string statements in bash" | ||
date: 2022-02-08 14:57:08 +0100 | ||
categories: bash | ||
excerpt: How to convert yes, no, true and false into a boolean in bash. | ||
#proccessors: pymd | ||
--- | ||
|
||
## Preface | ||
|
||
While writing a custom GitHub Action with a Docker entrypoint written in bash, | ||
I want the users to be able to pass boolean variables as `true` and `false`, | ||
`yes` and `no`, `1` and `0`, and en empty string being considered false. | ||
|
||
## Using a function with a regular expression | ||
|
||
I first went with `return 0` and `return 1` in the function, | ||
but I found this to increase my cognitive load due to `0` being success, i.e. | ||
true, and `1` being false. I found that returning a string gives for easier reading. | ||
|
||
```bash | ||
# Returns a string `true` if the string is considered a boolean true, | ||
# otherwise `false`. An empty value is considered false. | ||
function str_bool { | ||
local str="${1:-false}" | ||
local pat='^(true|1|yes)$' | ||
if [[ "$str" =~ $pat ]] | ||
then | ||
echo 'true' | ||
else | ||
echo 'false' | ||
fi | ||
} | ||
``` | ||
|
||
I can now configure my variables as booleans! | ||
|
||
```bash | ||
enable_debug_logging=$(str_bool "${ENABLE_DEBUG_LOGGING:-}") | ||
|
||
if [ "$enable_debug_logging" = "true" ] | ||
then | ||
# ... | ||
echo "Debug logging enabled!" | ||
fi | ||
``` |