Boolean Variables “True False” and Logical Operators in Bash

Boolean values like “true” and “false” are frequently used in Bash scripting to indicate success or failure. These variables work as flags to guide decision-making. When paired with logical operators like “&&” (AND) and “||” (OR), Bash scripts become more dynamic and adaptable. These operators allow you to execute specific commands based on the Boolean values, or the success or failure of earlier commands.

In this article, you will learn how to use the boolean “True False” variable with 4 different examples. So let’s start.

What are the True and False Values?

It is true that there are no Boolean expressions in bash. However, you can use a boolean variable value as 1 ( “False”) or 0 ( “True”) depending on your requirements. Further, bash supports Boolean expression conditions. So you can execute if else block with the help of a boolean variable. First, let’s check which types of values are boolean operators return.

To check the return value of the boolean variable, use this script:

#!/bin/bash

# Using 'true' to indicate success
true
echo "Exit code of 'true': $?"

# Using 'false' to indicate failure
false
echo "Exit code of 'false': $?"
EXPLANATION

This bash script uses the true command to indicate that the operation is successful. Then it uses an echo command to display the output of the true command, using the $? variable. Then, it uses the false command to show that the operation is a failure. It uses another echo statement to show the output of the $? Variable, stating “Exit code of ‘false’:” proceed by the return value of $? syntax.

what are the true and false in bash scriptAs you see from the image above, the code returns 0 when the code executes the ‘true’ command and 1 when it executes ‘false’ in the bash script.

4 Different Examples of Using Boolean Variables “True False” and Logical Operators in Bash

Boolean true and false are used in a wide range of situations, such as controlling script execution based on the command exit status, verifying user input, checking the existence of files/directories, organizing conditional execution of statements, and controlling loop conditions such as ‘while’ and ‘until’. In the following section, you will learn how to incorporate boolean ‘true false’ variables with different logical operators. You also get a sample code that will demonstrate how to count the number of lines in multiple text files in the later part of the article.

Example 1: Determining True or False with Logical “AND (&&)”

With the boolean true-false, you can do conditional execution. It means you can run different parts of your code depending on what the return value is. Let’s say we want to know which part of the if-else statement will be executed for which kind of boolean value ( 0 or 1).

#!/bin/bash

# Prompting for the user input
read -p "Enter 0 for success, 1 for failure: " user_input

# Using the AND operator to execute the second command only if the user_input is 0
if [ "$user_input" -eq 0 ] && echo "Executing command 1"; then
  echo "Command 1 succeeded"
else
  echo "Command 1 failed"
fi
EXPLANATION

This Bash script prompts the user to enter 0 for success or 1 for failure. It then uses the AND operator (&&) to conditionally execute a simulated “Command 1” only if the user enters 0. The script prints either “Command 1 succeeded” or “Command 1 failed” based on the user’s input.

Determining True or False with Logical AND (&&)As you can see, the code only executes the else block when the user inputs 1. If the user inputs 0, the code will execute the if block.

Example 2: Conditional Execution Using True or False with Logical “OR (||)”

You can also assign true-false to any variable and use it along with the Logical OR operator. Here is a sample code that demonstrates how you can use the logical OR operator with boolean true false to identify an even or odd number.

To determine the even or odd value in a bash script, use the following script:

#!/bin/bash

# Prompt user for a number
read -p "Enter a number: " number

# Check if the number is even or odd
isEven=false
1
[ "$((number % 2))" -eq 0 ] || isEven=true

# Display the result based on the true/false value
if $isEven; then
    echo "The number $number is odd."
else
    echo "The number $number is even."
fi
EXPLANATION

This Bash script prompts the user to enter a number and stores it in a variable called “number”. Additionally, the script initializes a boolean variable named “isEven” as false.

The core line of the script,  [ "$((number % 2))" -eq 0 ] || isEven=true, performs a modulo operation on the entered number to check if the remainder equals 0, which indicates an even number. If the condition is not met, meaning the number is odd, the logical OR (||) operator updates isEven to true.

Finally, it employs an if statement that uses the value of isEven to determine whether the entered number is even or odd. Depending on the outcome, the script prints the appropriate message.

Conditional Execution Using True or False with Logical OR ()As you can see, upon giving a user input, the code successfully returns its statement whether the given number is even or odd.

Example 3: Combining Logical “AND” and “OR” With True and False

Both the Logical AND and OR operator can be used along with the boolean ‘true false’ to make a decision based on the condition. For instance, to determine whether a given year is a leap year or not, you need the following script where both Logical AND and OR operators have been used along with boolean true false value:

#!/bin/bash

# Prompt user for a year
read -p "Enter a year: " year

# Determine whether the year is a leap year
isLeapYear=false

# Leap year conditions: divisible by 4, not divisible by 100 unless also divisible by 400
[ "$((year % 4))" -eq 0 ] && ( [ "$((year % 100))" -ne 0 ] || [ "$((year % 400))" -eq 0 ] ) && isLeapYear=true

# Display the result based on the logical AND and OR conditions
if $isLeapYear; then
    echo "The year $year is a leap year."
else
    echo "The year $year is not a leap year."
fi
EXPLANATION

This Bash script prompts the user for input, checks leap year conditions and uses a boolean variable isLeapYear to store the result. The script employs logical AND (&&) and OR (||) conditions to succinctly evaluate the leap year criteria. Finally, it prints the result based on the value of isLeapYear.

Combining Logical AND and OR with True and FalseFrom the image, when I give 2023 as the user input, the code states that 2023 is not a leap year. However, that code says 2024 is a leap year as the user variable “year” meets all the conditions of [ "$((year % 4))" -eq 0 ] && ( [ "$((year % 100))" -ne 0 ] || [ "$((year % 400))" -eq 0 ] ) && isLeapYear=true, therefore the code prints the if block.

Example 4: Checking the number of lines in Multiple Text Files With Boolean “True False” and Logical Operators

You can also use the boolean true false value more practically with the help of logical operators such as checking the number of lines in text files. For example, run ls -l

Checking the list of files and directories with wc -l commandHere, the image highlights two text files in the current folder. Now, the goal is to process all .txt files in the current directory and count the number of lines in each text file.

Now, to count the number of lines in each file, use the following script with the help of boolean true false variable:

#!/bin/bash

# Set the directory path
directory_path=$(pwd)

# Set boolean variable to control the loop
processFiles=true

# Check if the directory exists and the loop should be executed
if [ -d "$directory_path" ] && $processFiles; then
    # Loop through files in the directory
    for file in "$directory_path"/*.txt; do
        if [ -e "$file" ]; then
            echo "Processing file: $file"

            #Count the number of lines in the file
            line_count=$(wc -l < "$file")
            echo "Number of lines in $file: $line_count"
        fi
    done
else
    echo "Directory does not exist or loop condition is false. Exiting."
    exit 1
fi

echo "File processing completed."
EXPLANATION

The Bash script initializes a variable directory_path with the current working directory obtained using the pwd command. A boolean variable processFiles is set to control the loop. Then it checks if the directory specified by directory_path exists and if the loop condition $processFiles is true using the [ -d "$directory_path" ] && $processFiles expression. If both conditions are met, the script enters a loop that iterates through each .txt file in the directory. Within the loop, [ -e "$file" ] checks if the current file exists, and if true, the script processes the file by printing a message about its processing and counting the number of lines using wc -l. The final else block handles cases where the directory does not exist or the loop condition is false. It also displays an appropriate message and exits with an error code.

 Checking the number of lines in Multiple Text Files with Boolean “True False” and Logical OperatorsAs you see from the image above, the provided code successfully counts the number of lines of each text file, using a for loop along with the logical bash operator (AND) and the boolean ‘true false’ value in a bash script.

Best Practices of Working With Boolean “True False” Variables in Bash

  • Ensure that 0 is used for true and 1 is used for false to follow Unix conventions.
  • Ensure that the name of the boolean variable is meaningful and indicates its purpose.
  • When using a boolean variable in a conditional statement, always compare the values using the -eq operator.
  • When dealing with complex scripts, think about using functions to wrap related boolean operations. It makes the code easier to understand.

Conclusion

There are many ways to incorporate the boolean variable with a bash code. It depends on how you want to design and write your algorithm. I hope this article provides you with an overall idea of how to work with true false values in a bash script. However, If you have any confusion or queries, feel free to comment below. Thank You!

People Also Ask

What is true and false in Bash?

When it comes to Bash scripting, the true and false commands are crucial in representing boolean values that have a significant role in decision-making and control flow. The true command, upon execution, does not carry out any function but consistently returns a successful exit status (0). This makes it an essential tool for creating loops or as a placeholder in situations where no specific action is required. On the other hand, the false command, while equally inactive in terms of functionality, consistently returns a failure exit status (non-zero). This makes it particularly useful for simulating error conditions or intentionally causing a command to fail within a script.

What is true in shell script?

The true command does absolutely nothing and always returns a successful exit status. When this command is executed, it serves as a no-operation command. It produces no output and has no impact on the execution flow of the script. Its primary purpose is to indicate successful execution and always returns an exit code of 0. However, it is commonly used as a placeholder in scripts or as a command that ensures a successful exit status. This is especially useful in situations where a command is necessary but no specific action is required.

Is Bash exit code 0 true or false?

Bash exit code 0 means true. An exit code of 0 usually means that the command or script has been executed successfully without any errors. This is why it is commonly referred to as “true”. A zero exit code is generally considered a true condition, while a non-zero exit code implies a false condition. This convention is widely accepted and used.

Related Articles


<< Go Back to Bash Logical Operators | Bash Operator | Bash Scripting Tutorial

5/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment