Operators and Expressions

7. Operators and Expressions#

This chapter shows how Bash represents calculations, comparisons, tests, and logical expressions that scripts can use to make decisions.

  • Arithmetic: Use Bash integer operators for counters, offsets, and status checks.

  • Comparison: Choose numeric and string operators for the kind of value being tested.

  • File tests: Ask precise questions about files before acting on them.

  • Logic: Combine tests with AND, OR, and NOT.

  • Conditionals: Place expressions inside if, case, and short-circuit command patterns.

Chapter Video

What are Conditional Statements in Bash (5:02) by Microsoft Developer

Hosted on YouTube; property of its original creator, embedded here for educational reference only.

Learning Objectives

By the end of this chapter, you will be able to:

  1. Use arithmetic operators and arithmetic expansion.

  2. Choose numeric, string, and file-test operators correctly.

  3. Combine tests with logical operators.

  4. Use expressions safely inside conditional logic.

Chapter Flow

Glossary

#

Term

Explanation

1

Operator

A symbol or keyword that performs a comparison, calculation, or logical operation.

2

Expression

A combination of values and operators evaluated by Bash.

3

Arithmetic expansion

The $((...)) form used to evaluate integer arithmetic.

4

Integer division

Division that discards any fractional result.

5

Modulo

The remainder operator %, often used for divisibility tests.

6

Numeric comparison

A test using operators such as -eq, -ne, -lt, and -gt.

7

String comparison

A test comparing text values with operators such as =, !=, <, or >.

8

Logical AND

A condition that succeeds only when both parts succeed.

9

Logical OR

A condition that succeeds when either part succeeds.

10

Logical NOT

A condition that reverses success and failure.

11

test

A command that evaluates expressions, also written as [ ... ].

12

Double brackets

The Bash [[ ... ]] conditional expression syntax.

13

File test

A test such as -e, -f, or -d that checks file properties.

14

Exit status

A numeric result where 0 means success and nonzero usually means failure.

15

Short-circuit evaluation

Evaluation that skips later commands when the result is already determined.

16

Unary test

A test with one operand, such as -z string.

17

Binary test

A test comparing two operands.

18

Pattern matching

Matching text against shell-style patterns inside conditionals.

19

Readable test

The -r file test, which checks read permission.

20

Executable test

The -x file test, which checks execute permission.