How can I declare and use Boolean variables in a shell script?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In shell scripting, Boolean variables are used to control the flow of execution in scripts, enabling conditional behavior based on whether conditions are true or false. Unlike some programming languages that have a dedicated Boolean data type (true and false), shell scripting primarily relies on exit status codes to represent Boolean variables — where 0 (zero) typically indicates success (true), and any non-zero value indicates failure (false).
Declaring Boolean Variables
In shell scripts, you don’t formally declare a data type. Variables can be treated as Booleans by considering their values in conditional expressions. The typical practice is to use commands that return exit statuses and to evaluate these statuses directly in conditional statements.
Here's how you can set and use Boolean-like variables:
In the above example, file_exists is a string that represents a Boolean condition by convention rather than by data type. The actual check for file existence is performed by the [ -e "/path/to/your/file" ] command, which sets the variable.
Working with Exit Statuses
More traditionally, shell scripts use exit statuses directly for Boolean expressions like this:
Here, the [ -e "/path/to/your/file" ] command itself checks whether a file exists (true if it does, false otherwise), directly influencing the flow of the if-else statement.
Using Boolean Operators
Shell scripts also support Boolean operators such as && (AND) and || (OR) which allows combining multiple conditions:
Using the test Command
The test command evaluates the expression provided to it and exits with a status code (0 if true, non-zero if false). It is equivalent to using [ expression ].
Negating Conditions
You can negate a condition using !, which inverses the truthiness of an expression:
Summary Table
| Concept | Syntax | Description | ||
| Direct Condition | if [ condition ]; then ... fi | Executes based on the evaluation of condition. | ||
| AND Operator | if [ cond1 ] && [ cond2 ]; then ... fi | True if both conditions are true. | ||
| OR Operator | if \[ cond1 ] | | \[ cond2 ]; then ... fi | True if at least one condition is true. | ||
| Negation | if ! [ condition ]; then ... fi | True if the condition is false. | ||
| Test Command | if test condition; then ... fi | An alternative to [ condition ]. |
Conclusion
In shell scripting, Boolean variables and expressions are fundamental for directing the flow of scripts based on conditions. Understanding how to use these alongside conditional statements, logical operators, and the test command, is crucial for effective scripting.

