How to Assign Boolean Expressions to Variables in Bash

Written by: Madhur Batra   |   Last updated: July 23, 2023

Introduction

Unlike other programming languages, Bash doesn't have a straightforward concept of boolean variables. However, we can simulate boolean variables in Bash by either integers (where 0 represents true and non-zero represents false) or strings ("true" and "false").

In this guide, we learn about assigning boolean expressions to variables in Bash.

Represent boolean variables in Bash

Let's look in detail at how to use integers and strings to represent boolean variables in Bash.

2.1 Using integers for representing Booleans

In Bash, integers are commonly used to represent boolean values. We can use the integer values 0 and 1 to represent true and false values respectively. This concept of 0 and 1 comes because in a Unix-like system 0 is for success and non-zero error code is for failure.

Example:

#!/bin/bash

# Representing boolean values with integers
trueVal=0
falseVal=1

if [ $trueVal -eq 0 ]; then
        echo "trueVal: $trueVal, the condition is true"
fi

if [ $falseVal -eq 1 ]; then
        echo "falseVal: $falseVal, the condition is false"
fi

Using the `-eq` operator, we can perform comparisons on the integer values.

Executing the script:

$ ./integerBooleans.sh
trueVal: 0, the condition is true
falseVal: 1, the condition is false

2.2 Using strings for representing Booleans

Similarly, we can use strings for simulating boolean variables by assigning string values “true” or “false” to the variables.

Example:

#!/bin/bash

# Representing boolean values using strings
trueVal=true
falseVal=false

if [ "$trueVal" == true ]; then
        echo "The condition is true"
fi

if [ "$falseVal" == false ]; then
        echo "The condition is false"
fi

We can perform the string comparisons using the `==` operator to form logical blocks.

Executing the script:

$./stringBooleans.sh
The condition is true
The condition is false

3. Assigning boolean expressions in Bash

Bash provides a special built-in variable `$?` that stores the exit status of the last executed command. A zero value of the exit status represents a successful execution while a non-zero value indicates that some error was encountered.

We can make use of this exit status value to form boolean expressions in Bash.

3.1 Evaluating string and arithmetic expressions as boolean values

When working with text files, string comparison is an operation that is frequently performed. Let’s take an example to understand how we can represent string comparisons as boolean values.

#!/bin/bash

str="stringExample"

# Unequal strings
[ $str = "stringExampel" ]
echo $?

# Equal strings
[ $str = "stringExample" ]
echo $?

We define a string variable and perform two comparisons. Using unequal strings in the first case and equal strings in the second case. 

Let’s observe the output on running the script.

$./stringComparisons.sh
1
0
  • In the first case, the exit status = 1 is printed to the stdout which indicates the string match command failed since the strings are unequal.
  • Whereas, in the second case, the exit status = 0 indicates the command ran successfully since the strings are equal.

Let’s take another example using arithmetic expressions to create boolean values.

#!/bin/bash

num=5

# Unequal numbers
[ $num = 4 ]
echo $?

# Equal numbers
[ $num = 5 ]
echo $?

Let’s observe the output on running the script.

$./intComparisons.sh
1
0

Similar to the previous example, observe that the exit status is 1 for an unequal number comparison and 0 for an equal comparison.

3.2 Representing results from file and directory operations as boolean values

File and directory operations such as checking the file existence, the file execution modes, and owners are another set of operations that are often used to create logical blocks in Bash scripting.

Let’s take an example to understand how we can create boolean variables using these operations.

$ ls
fileOperations.sh  integerBooleans.sh      stringBooleans.sh
intComparisons.sh  matchFruitStatement.sh  stringComparisons.sh

$ pwd
/home/linuxopsys/bashBooleans

$ [ -d /home/linuxopsys/bashBooleand ]
$ echo $?
1

$ [ -d /home/linuxopsys/bashBooleans ]
$ echo $?
0

The command [ -d <FILENAME> ] checks for the existence of directory and the status code is set to 0 if the directory exists and 1 if it does not.

$ [ -f ./textFile.sh ]
$ echo $?
1
$ [ -f ./fileOperations.sh ]
$ echo $?
0

Here, we check for the existence of a file. Similar to `-d` flag, status code is 0 if the file exists and 1 if it does not.

$ [ -w fileOperations.sh ]
$ echo $?
1

$ chmod a+w fileOperations.sh
$ echo $?
0

This is another helpful command. The flag `-w` checks if the file is write-able or not and sets the status code to 0 or 1 respectively.

4. Using logical operators with Bash boolean expressions

Bash has built-in support for the logical operators - AND (&&), OR (||), NOT (!). These operators can be used to form complex conditions from simple boolean expressions.

Let’s take an example to understand this further:

#!/bin/bash

age=22
favoriteColor="red"

#1 - Using &&
if [ $age -gt 18 ] && [ "$favoriteColor" == "yellow" ]; then
        echo "Boolean condition using && satisfied"
else
        echo "Boolean condition using && unsatisfied"
fi

#2 - Using ||
if [ $age -gt 18 ] || [ "$favoriteColor" == "yellow" ]; then
        echo "Boolean condition using || satisfied"
else
        echo "Boolean condition using || unsatisfied"
fi

#3 - Using !
if ! [ "$favoriteColor" == "yellow" ]; then
        echo "The condition is invalid."
fi
$ ./logicalOperators.sh
Boolean condition using && unsatisfied
Boolean condition using || satisfied
The condition is invalid.
  • In the first example, using the AND operator, the compound expression becomes false due to the condition [ "$favoriteColor" == "yellow" ]
  • Whereas, in the second example, using the OR operator the [ $age -gt 18 ] equates to true and hence the compound expression becomes true.
  • In the third example, [ "$favoriteColor" == "yellow" ] evaluates to false, but the NOT operator flips the condition to true.

5. Practical examples

Let’s take some real-world examples to understand the utility of boolean expressions in Bash scripts.

Example #1

Creating a simple script that matches a list of fruits to its most appropriate related statement.

#!/bin/bash

# Create an array of fruit strings
fruits=("apple" "banana" "orange")
i=1

# Match each fruit to its most appropriate statement
for fruit in "${fruits[@]}"
do
        echo "Iteration $i, fruit: $fruit"
        [ $fruit = "apple" ]
        if [ $? -eq 0 ]; then
                echo "An apple a day keeps the doctor away"
        fi

        [ $fruit = "banana" ]
        if [ $? -eq 0 ]; then
                echo "Monkeys are banana thieves"
        fi

        [ $fruit = "orange" ]
        if [ $? -eq 0 ]; then
                echo "Oranges are a great source of Vitamin C"
        fi
        i=$(($i+1))
done

We iterate over the list of fruits in an array and compare each fruit element using the string comparison method.

The exit status from the comparisons is used to form boolean expression, which can be used in the if blocks utilizing the -eq operator.

Observe the output on running the script.

$. /matchFruitStatement.sh
Iteration 1, fruit: apple
An apple a day keeps the doctor away
Iteration 2, fruit: banana
Monkeys are banana thieves
Iteration 3, fruit: orange
Oranges are a great source of Vitamin C
  • In the first iteration of the loop, list element is apple which matches the first comparison and exit status = 0. The exit status for the second and third comparisons evaluates to 1. Thus only the first if block is executed.
  • Similarly, in the second and third iterations, the list elements are banana and orange which match the second and third comparisons respectively and the corresponding if blocks are executed.

Example #2

Creating a script that checks the file mode of an executable file.

$ pwd
/tmp
$ echo -e '#!/bin/bash\n\necho "Output from execFile: Hello World"' > ./execFile
$ ls -l
total 4
-rw-rw-rw- 1 root linuxopsys 32 Jul 10 19:51 execFile

We create a simple bash script named execFile in the /tmp directory that prints “Hello world”. By default, it is non-executable.

Now, let’s add another bash script that can invoke this script.

#!/bin/bash

isExec=$( [ -x "/tmp/execFile" ]; echo $? )
echo $isExec
if [ $isExec -eq 0 ]; then
echo "If the file is executable, invoke it"
          	( /tmp/execFile )
else
echo "Make the file executable and invoke it"
            sudo chmod a+x /tmp/execFile
            /tmp/execFile
fi

We use command substitution to assign boolean expressions here.

  • The command isExec=$( [ -x "/tmp/execFile" ]; echo $? ) checks if the file execFile is an executable and assigns the status code of this command to the isExec variable.
  • The operator `-eq` is used to compare the status codes. If it is 0, the file is executable and is directly invoked. Else, we change the file mode and then execute it.

Let’s observe the output on running the script:

$ ./invokeExecFile.sh
Make the file executable and invoke it
Output from execFile: Hello World
$ ls -l
total 4
-rwxrwxrwx 1 root linuxopsys 32 Jul 10 19:51 execFile

Since the execFile was non-executable by default, the script changed the mode and then invoked it.

Let’s see what happens when we invoke the script the second time.

$ ./invokeExecFile.sh
If the file is executable, invoke it
Output from execFile: Hello World

This time, execFile is directly invoked since it is already an executable.

About The Author

Madhur Batra

Madhur Batra

Madhur Batra is a highly skilled software engineer with 8 years of personal programming experience and 4 years of professional industry experience. He holds a B.E. degree in Information Technology from NSUT, Delhi. Madhur’s expertise lies in C/C++, Python, Golang, Shell scripting, Azure, systems programming, and computer networking. With a strong background in these areas, he is well-equipped to tackle complex software development projects and contribute effectively to any team.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment