I know that bash doesn't support boolean variables, so how do people typically represent a value that needs to be used later, and that can be truthy or falsey? From this question, some ways seem to be calling out to the true
/false
programs via a variable, doing string comparison in an if, and using a case statement. Are these what bash programmers commonly use, or are there other methods I'm not considering?
Asked
Active
Viewed 93 times
0

Christopher Shroba
- 7,006
- 8
- 40
- 68
-
1Does this answer your question? [How can I declare and use Boolean variables in a shell script?](https://stackoverflow.com/questions/2953646/how-can-i-declare-and-use-boolean-variables-in-a-shell-script) – Ari Fordsham Sep 13 '20 at 14:11
-
Note that true and false are builtin commands, so there's no performance penalty for using them. – glenn jackman Sep 13 '20 at 20:13
1 Answers
1
Just expanding the ideas in your question:
the true
/false
commands
bool=true
if $bool; then echo Y; else echo N; fi # => Y
string value
bool="yes"
if [[ $bool == "yes" ]]; then echo Y; else echo N; fi # => Y
string emptiness
bool=""
if [[ $bool ]]; then echo Y; else echo N; fi # => N
zero/non-zero integer
bool=0
if ((bool)); then echo Y; else echo N; fi # => N
There's also a form using the boolean control operators:
((bool)) && echo Y || echo N
You have to be a bit careful with A && B || C
-- C will execute if either A or B fails.
With if A; then B; else C; fi
the only time C runs is if A fails, regardless of what happens with B.
Given
A() { echo A; }
B() { echo B; return 1; }
C() { echo C; }
Then
$ A && B || C
A
B
C
$ if A; then B; else C; fi
A
B

glenn jackman
- 238,783
- 38
- 220
- 352
-
This is a community wiki answer, so feel free to add any other methods. – glenn jackman Sep 13 '20 at 22:21