Skip to content

Commit

Permalink
post: bash boolean string statements
Browse files Browse the repository at this point in the history
  • Loading branch information
stigok committed Feb 8, 2022
1 parent 8bb57e9 commit ddba444
Showing 1 changed file with 47 additions and 0 deletions.
@@ -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
```

0 comments on commit ddba444

Please sign in to comment.