Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:
Best Practice to Represent Boolean Value in Shell Script
Last updated: December 22, 2024
1. Introduction
A shell script doesn’t have any concept of a boolean datatype. Instead, we can construct boolean variables, which allows us to store and handle true or false values as boolean values. The best practice to represent a boolean value most likely depends on the use case of a script.
In this tutorial, we’ll discuss best practices for representing a boolean value in a shell script.
2. Representation of a Boolean Value
Conventionally, but not always, any integer value that is 0 is regarded as false, while any non-zero integer is considered true, in the context of Bash scripts. We’ll be sticking with this convention in the examples that follow.
2.1. Declaring and Using Boolean Variables
Although shell scripts don’t have a native boolean datatype, we can emulate boolean behavior using variables.
To illustrate, let’s use an example:
#!/bin/bash
is_active=true
# Using the boolean variable in an if condition
if [ "$is_active" == true ]; then
echo "The feature is active."
else
echo "The feature is inactive."
fi
Let’s understand the above script:
- is_active=true – declares a variable named is_active and assigns the value true to it
- if [ “$is_active” == true ]; then – checks if the value of the is_active variable is equal to true; if it’s true, we print the message The feature is active, otherwise, we print the message The feature is inactive
Above, the variable is_active mimics a boolean value, allowing us to implement boolean-like logic in shell scripts.
2.2. Integer as Boolean Value
The boolean values can be presented as integers (0 or 1) when a particular condition needs to be tested. To demonstrate that, we’ll go over some examples.
For our first example, let’s look at the contents of our example.sh Bash file:
#!/bin/bash
val=0
if [ $val -eq 1 ]; then
echo "True"
else
echo "False"
fi
Let’s break down the script above:
- if [ $val -eq 1]; then – the if condition executes with the help of the -eq conditional operator that checks whether the value of variable val is equal to 1 or not
- echo “True” – the echo statement prints True as boolean output
- else – the other part of the statement that is executed if the condition is not met
- echo “False” – the echo statement prints False as boolean output
- fi – represents the closure of the if statement
Now, let’s execute the Bash script and see its output:
$ bash example.sh
$ True
Other than an if-else statement, the integer boolean values work best with loops.
2.3. Integer as Boolean Value Using Loops
Let’s see an example in which we execute a while loop using the integer boolean value.
Let’s say we have a variable continue that represents a boolean integer value 0 (False):
#!/bin/bash
continue=0
count=0
while [ $continue -eq 0 ]; do
count=$((count + 1))
echo "count $count Running ..."
if [ $count -ge 3 ]; then
continue=1
fi
sleep 1
done
echo "Completed..."
Now, let’s explore the script we’ve used within this example:
- count=0 – a variable to count the loop increments (total number of times a loop executes itself)
- while [ $continue -eq 0]; do – the while loop iterates through the -eq conditional operator until the value of the variable continue is equal to 0
- count=$((count + 1)) – append 1 to the original value of variable count every time a loop iterates
- echo “count $count Running…” – display each iteration number
- if [ $count -ge 3 ]; then – the if statement executes with the -ge conditional operator only when the value of variable count is greater than or equal to 3
- continue=1 – the variable continue is set to boolean integer 1 (true) when the count reaches 3
- fi – stipulates the closure of the if statement
- sleep – the sleep function causes the script to sleep for 1 second
- done – specifies the closure of the while loop
- echo “Completed…” – the echo statement prints Completed… as we pop out from the loop
Now, let’s see the output of the Bash script:
count 1 Running ...
count 2 Running ...
count 3 Running ...
Completed...
Here’s what we’ve learned from the above output:
- As the value of a boolean variable continue is 0 and count is less than 3, the while loop continues to execute. Therefore, the echo statement is executed 3 times in total.
- As the value of the count variable reaches 3, the variable continue is set to 1, negating the while loop’s condition. Thus, the while loop ends, and the last echo statement executes and outputs Completed…
2.4. String as Boolean Value
Other than integers, boolean values can be presented as strings, true or false.
Let’s see an example of using a string as a boolean value in a Bash script.
To demonstrate, we’re using the environment variable $RANDOM to identify whether the random integer value is even or odd:
#!/bin/bash
r=$RANDOM
echo "Random Number: $r"
if (( r % 2 == 0 )); then
isEven="true"
else
isEven="false"
fi
echo "Is $r Even? : $isEven"
Let’s have a look at the Bash code we’ve used within this illustration:
- r=$RANDOM – A random number generated by the built-in $RANDOM variable is initialized as a value to the variable r
- echo “Random Number: $r” – prints the generated value using the RANDOM variable
- if (( r % 2 == 0 )); then – the condition verifies that the modulus of the random number stored in the variable r equals the integer 0 using the == operator
- isEven=”true” – variable isEven that is set to string true as a boolean value in case the if condition is satisfied
- isEven=”false” – variable isEven set to string false as a boolean value in case the if condition is not satisfied
- echo “Is $r Even? : $Even” – prints whether a randomly generated value through the $RANDOM variable is even or not using the boolean variable $isEven
Now, let’s execute the file example.sh:
Random Number: 18188
Is 18188 Even? : true
In return, the script has been successfully executed, identifying the random number 18188 as an Even value.
2.5. Exit Statuses in Function
To enhance a script’s modularity, we can use functions with the exit statements and control the execution flow of a shell script.
The exit code return 0 represents the success of a script without any errors in Unix-based systems, whereas the exit code return 1 represents the failure of a script when a particular error is found or a condition isn’t met.
Let’s have a Bash illustration for using exit statuses in the function.
To demonstrate, we’re creating a file alpha.sh within the current working directory and using it within the script via the variable fname:
#!/bin/bash
fname="alpha.sh"
testfunc() {
if [ -e "$fname" ]; then
return 0
else
return 1
fi
}
testfunc
if [ $? -eq 0 ]; then
echo "File exists"
else
echo "File doesn't exist"
fi
Now, let’s explore the Bash code below:
- testfunc() – a user-defined function
- if [ -e “name”]; then – verifies the existence of the file alpha.sh in the working directory using the variable fname and the -e operator
- return 0 – exit code to continue program execution when a condition satisfies
- return 1 – exit code to terminate the program execution
- testfunc – a function call to run the testfunc() function
- If [ $? -eq 0 ]; then – use of $? to capture the exit code returned by the function, compare it with the value 0 via the -eq operator, and execute accordingly
- echo “File exists” – prints File exists in case of exit code 0
- echo “File doesn’t exist” – prints File doesn’t exist in case of exit code 1
On running the above Bash script, this is what we can learn from the output:
File doesn’t exist
The file alpha.sh doesn’t exist in the current working directory; thus, the testfunc() returns the exit status 1.
After capturing the exit code 1 from the function, the else part of the if-else statement is executed, and prints File doesn’t exist.
3. Conclusion
In this article, we’ve seen a few ways to represent boolean values in Bash scripts. These include using integers 0 and 1 or the strings true and false as boolean values.
Lastly, the exit status codes return 0 and return 1 are used as examples to demonstrate their working in functions to enhance modularity. We can choose between the different techniques based on preference or the given use case.