</>
Skip to content
Bash lessons (10/29)

Bash — Operators

Arithmetic operators

#!/bin/bash

a=10
b=3

echo "$((a + b))"   # 13
echo "$((a - b))"   # 7
echo "$((a * b))"   # 30
echo "$((a / b))"   # 3
echo "$((a % b))"   # 1

String comparison

#!/bin/bash

[ "abc" = "abc" ] && echo "Equal"
[ "abc" != "xyz" ] && echo "Not equal"
[ "abc" \< "xyz" ] && echo "Less than"
[ "xyz" \> "abc" ] && echo "Greater than"
[ -z "" ] && echo "Empty"
[ -n "abc" ] && echo "Non-empty"

File test operators

#!/bin/bash

file="/etc/passwd"

[ -f "$file" ] && echo "Regular file"
[ -d "$file" ] && echo "Directory"
[ -r "$file" ] && echo "Readable"
[ -w "$file" ] && echo "Writable"
[ -x "$file" ] && echo "Executable"
[ -s "$file" ] && echo "Non-empty"

Logical operators

#!/bin/bash

a=10
b=20

# AND
[ $a -gt 5 ] && [ $b -gt 15 ] && echo "Both true"

# OR
[ $a -gt 15 ] || [ $b -gt 15 ] && echo "At least one true"

# NOT
[ ! $a -gt 15 ] && echo "a is not greater than 15"

Combined test

#!/bin/bash

a=10
b=20

# AND with &&
[ $a -gt 5 ] && [ $b -gt 15 ] && echo "Both true"

# OR with ||
[ $a -gt 15 ] || [ $b -gt 15 ] && echo "At least one"

# NOT with !
[ ! $a -gt 15 ] && echo "Not greater"

Mini Practice

Write Bash code that:

  1. Compares two strings
  2. Tests if a file exists and is readable
  3. Combines conditions with && and ||
  4. Uses the NOT operator

Up Next

In the next lesson, you'll learn about If Else — conditional branching in Bash.

Related Topics

Frequently Asked Questions about Operators

What is Operators in Bash?

Operators is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Operators?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Operators.

Why is Operators important in Bash?

Operators is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.