Understanding Boolean Variables in Bash Scripts 0️⃣1️⃣

Learn how to declare and use boolean variables (True or False) in bash scripts on Unix-like systems. Enhance your shell scripting skills 📈

Using Boolean Variables in Bash Scripts

Bash scripts allow automation of tasks on Linux and Unix-like systems. An important aspect of scripting is being able to execute commands conditionally based on various logic tests. While Bash does not have a dedicated Boolean data type, Boolean logic can still be implemented in Bash scripts by carefully using string and integer variables and comparison operators. This article will explain how to declare and use Boolean variables in Bash scripts.

Declaring Boolean Variables

Since Bash variables do not have types, Boolean values must be represented using strings or integers. Here are some ways to declare Boolean variables in Bash:

boolVar="true" # String value anotherVar="false" boolVar=1 # Integer value anotherVar=0

The values “true”/”false” or 1/0 are conventions for representing true/false states, but any non-empty string or non-zero integer could be used. Some advantages of strings are readability and ability to echo the value. Integers allow numeric comparison operators like -eq.

The special variable $? contains the exit status of the previously executed command, which can also act as a Boolean:

if [[ $? -eq 0 ]]; then echo "Previous command succeeded" else echo "Previous command failed" fi

Using Boolean Variables in Conditionals

The main way Boolean variables are used in Bash is in conditional statements like if to execute code selectively:

boolVar="true" if [[ $boolVar == "true" ]]; then echo "boolVar is true" fi

The [[ ]] test construct is preferred over [ ] for portability and flexibility. Other comparison operators like !=, >, < can be used for numeric values.

Logical operators further allow combining conditions:

if [[ $boolVar == "true" && $anotherVar == "false" ]]; then echo "boolVar is true AND anotherVar is false" fi

Logical operators:

  • ! – Negates the test, like NOT
  • && – Logical AND
  • || – Logical OR

Converting Between String and Integer Booleans

Since different tests work on strings vs integers, it can be useful to convert between representations:

strBool="true" intBool=0 # String -> Integer if [[ $strBool == "true" ]]; then intBool=1 else intBool=0 fi # Integer -> String if [[ $intBool -eq 1 ]]; then strBool="true" else strBool="false" fi

This allows flexibility in how Boolean values can be evaluated.


Here are some examples of using Boolean variables in a Bash script:

Testing command success

mkdir tempDir if [[ $? -eq 0 ]]; then echo "Directory created successfully" else echo "Directory creation failed!" exit 1 fi

Validating user input

read -p "Enter y/n: " ans if [[ $ans == "y" ]]; then echo "Proceeding..." elif [[ $ans == "n" ]]; then echo "Aborting..." exit 1 else echo "Invalid input" >&2 exit 1 fi

Combining conditions

var1="true" var2="false" if [[ $var1 == "true" && $var2 == "false" ]]; then echo "Expected booleans" else echo "Unexpected boolean values" exit 1 fi

Using Brackets for Tests

Bash provides different bracket syntaxes for evaluating conditional expressions. The [ and [[ commands can be used to test variables and implement Boolean logic.

The [ bracket is more portable across different shells, but [[ adds some useful features in Bash like pattern matching and regular expression support. Some key differences in syntax:

# Legacy [ bracket if [ "$boolVar" == "true" ]; then # [[ bracket bashism if [[ $boolVar == "true" ]]; then

The [ command is more strict about spacing and quoting. So for portability [ may be preferable, but for added features [[ is commonly used.

Operator Precedence

The order of operations matters when combining multiple Boolean conditions. Bash evaluates certain operators like ! and && before others like ||.

Parentheses can explicitly control grouping:

# ! has higher precedence than || if [[ ! $var1 || $var2 ]]; then # Explicit grouping if [[ (! $var1) || $var2 ]]; then

Understanding Bash operator precedence helps ensure logic executes as intended.

Nesting Conditionals

Conditionals like if statements can be nested to implement more complex Boolean logic:

if [[ $var1 == "true" ]]; then if [[ $var2 == "false" ]]; then echo "var1 is true and var2 is false" fi elif [[ $var1 == "false" ]]; then if [[ $var2 == "true" ]]; then echo "var1 is false but var2 is true" fi fi

Nesting conditionals builds on simple true/false tests to support complex expressions.

Example Boolean Expressions

Here are some examples of Boolean logic using Bash conditionals and operators:

# AND Logic if [[ $var1 == "true" && $var2 != "false" ]]; then echo "var1 is true AND var2 is not false" fi # OR Logic if [[ $var1 == "false" || $var2 == "true" ]]; then echo "var1 is false OR var2 is true" fi # NOT Logic if [[ ! ($var1 == "true" && $var2 == "true") ]]; then echo "NOT (var1 is true AND var2 is true)" fi

Mixing AND/OR/NOT allows replicating the common Boolean logic functions.

Validating Usernames

A common task is validating if a string matches an expected format, like a username:

usernameRegex="^[a-zA-Z0-9_]{3,16}$" read -p "Enter username: " username if [[ $username =~ $usernameRegex ]]; then echo "Valid username" else echo "Invalid username format" fi

Here a regular expression pattern is used to define a valid username string. The =~ operator checks if the input matches the regex.

Boolean Arithmetic

Bash also supports arithmetic expansion using $(()) and $[ ] syntax:

#Evaluate 1 + 1 if [[ $( (1 + 1) ) -eq 2 ]]; then echo "Equal" fi if [[ $[1 + 1] -eq 2 ]]; then echo "Equal again" fi

This allows doing arithmetic comparisons to implement Boolean logic. Any non-zero result evaluates as “true”.

Using && and ||

The && and || operators allow composing Boolean expressions:

# AND logic [[ $expr1 ]] && [[ $expr2 ]] # OR logic [[ $expr1 ]] || [[ $expr2 ]]

This provides an alternative to if-statements for simple Boolean logic:

# AND example [[ -f "$file" ]] && echo "File exists" # OR example [[ -z "$value" ]] || echo "Value is empty"

Validating Integers

A common task is validating if a value is an integer within a expected range:

read -p "Enter a number 1-10: " num # Check if integer if [[ $num =~ ^[0-9]+$ ]]; then # Check range if [[ $num -ge 1 && $num -le 10 ]]; then echo "Valid number" else echo "Out of range" fi else echo "Not a number" fi

This shows how string regex matching and arithmetic comparison can combine to validate numeric input.


While Bash lacks dedicated Boolean types, it compensates by facilitating Boolean logic using string and integer variables, along with a range of comparison and logical operators. With a bit of finesse, you can store and assess values as true or false conditions, effectively wielding conditional logic in your Bash scripts.

In Bash, integers can serve as boolean values, with 0 representing false and any non-zero value signifying true. This concept enables you to make decisions within your scripts based on variable evaluations. You can utilize various conditional operators such as the equal (==), not equal (!=), less than (<), and greater than (>) operators to compare values and establish logical conditions. Logical operators like ‘&&’ (AND) and ‘||’ (OR) allow you to string together multiple conditions to create complex decision structures within your scripts.

This flexibility empowers Bash scriptwriters to create dynamic and responsive programs. By thoughtfully employing these mechanisms, you can implement robust conditional logic in your Bash scripts, enabling your code to respond intelligently to changing circumstances and user inputs.

Android | Linux | SDL - Narrow Escape
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: