Skip to main content
Shell Scripting – Complete Beginner to Advanced Guide
CHAPTER 04 Intermediate

Working with Operators

Updated: May 16, 2026
25 min read

# CHAPTER 4

Working with Operators

1. Introduction

Because a Shell is fundamentally a text interpreter, it does not naturally understand mathematics or logic. If you type x=5>3, the shell sees a string of text; it does not evaluate a true/false mathematical equation. To empower our scripts to calculate disk usage quotas, verify password lengths, or validate file existence, we must utilize Operators. Operators are specific symbols and flags that force the shell to perform calculations and comparisons. In this chapter, we will master Arithmetic Operators using the legacy expr engine, decipher Relational (numeric) Operators like -eq, explore String matching (=, !=), and utilize File Test Operators to interrogate the physical hard drive.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Perform basic integer math using Arithmetic Operators and the expr command.
  • Compare numeric values using Relational Operators (-eq, -gt, -lt).
  • Compare text variables using String Operators (=, !=, -z).
  • Interrogate the filesystem logically using File Test Operators (-f, -d, -r).
  • Combine logic using Boolean AND/OR Operators (-a, -o).

3. Arithmetic Operators (Math)

In pure POSIX sh scripting, you must use the expr (Expression) command to perform math. *CRITICAL SYNTAX:* You must include strict spaces around the mathematical symbols!
sh
123456789101112131415
#!/bin/sh
A=10
B=5

# Addition
SUM=$(expr $A + $B)
echo "Addition: $SUM"

# Subtraction
SUB=$(expr $A - $B)

# Multiplication (Requires escaping the asterisk with a backslash!)
# If you don't use \*, the shell thinks it means "all files in this directory".
MULT=$(expr $A \* $B)
echo "Multiplication: $MULT"

4. Relational Operators (Numeric Comparison)

When comparing two numbers in a Shell script, you do not use < or >. You must use letter codes inside square brackets [ ].
  • -eq : Equal to
  • -ne : Not Equal to
  • -gt : Greater Than
  • -ge : Greater Than or Equal To
  • -lt : Less Than
  • -le : Less Than or Equal To
sh
123456
#!/bin/sh
CPU_LOAD=85

# Check if CPU is greater than 80
[ $CPU_LOAD -gt 80 ]
# (In the next chapter, we will wrap this inside an 'if' statement to make decisions!)

5. String Operators (Text Comparison)

When comparing text, the rules change. We switch back to traditional math symbols.
  • = : Strings are exactly identical. (Note: standard sh uses a single =, while bash allows ==).
  • != : Strings are not identical.
  • -z : String is empty (Zero length).
  • -n : String is NOT empty (Non-zero length).
sh
12345
#!/bin/sh
USER_ROLE="admin"

# Check if role exactly equals "admin"
[ "$USER_ROLE" = "admin" ]

6. File Test Operators

These are the most utilized operators in system administration. They check the physical state of the hard drive.
  • -f : True if the path is a normal File.
  • -d : True if the path is a Directory (folder).
  • -r : True if the file has Read permission.
  • -w : True if the file has Write permission.
  • -x : True if the file is Executable.
  • -s : True if the file size is greater than 0 bytes (not empty).
sh
12345
#!/bin/sh
LOG="/var/log/syslog"

# Check if the log file exists and is a regular file
[ -f "$LOG" ]

7. Boolean Operators (AND / OR)

Sometimes you need to check two things at the same time.
  • -a (Logical AND): Both conditions must be True.
  • -o (Logical OR): At least one condition must be True.
sh
123456
#!/bin/sh
AGE=25
CITIZEN="yes"

# Check if age > 18 AND citizen = "yes"
[ $AGE -gt 18 -a "$CITIZEN" = "yes" ]

8. Diagrams/Visual Suggestions

*Visual Concept: The Operator Translation Matrix* Create a visual table showing standard math symbols on the left, and their Shell equivalents on the right.
  • == (Math) -> -eq (Shell Numeric) -> = (Shell String)
  • > (Math) -> -gt (Shell Numeric)
This matrix is vital because beginners constantly attempt to use < and > for numeric comparisons, which results in catastrophic file redirection errors.

9. Best Practices

  • Quote Strings in Comparisons: When using [ "$VAR" = "Text" ], ALWAYS wrap the variable in double quotes. If the variable is empty or contains a space, failing to use quotes will break the bracket syntax and crash the script with a "too many arguments" error.

10. Common Mistakes

  • Using < or > for numbers: If you type [ 10 > 5 ] in a shell script, the shell sees the > symbol and assumes you want to perform output redirection (Chapter 9). It will literally create a text file named 5 in your current directory! Always use -gt and -lt for numbers.

11. Mini Project: The Calculator and Verifier

Let's build a script that uses operators to verify files and perform math.
  1. 1. nano verify.sh
  1. 2. Write the code:
sh
1234567891011121314151617181920212223
#!/bin/sh

FILE="data.txt"

# Create a dummy file so the script works
touch "$FILE"

echo "1. Performing Math Operation..."
VAL1=50
VAL2=25
RESULT=$(expr $VAL1 / $VAL2)
echo "$VAL1 divided by $VAL2 is: $RESULT"

echo "2. Testing numeric relation..."
# Test if result is equal to 2 (Silent test)
[ $RESULT -eq 2 ] && echo "Math verification passed!"

echo "3. Testing File Operators..."
# Check if file exists AND has write permission
[ -f "$FILE" -a -w "$FILE" ] && echo "File $FILE is ready for data injection."

# Cleanup
rm -f "$FILE"
  1. 3. chmod +x verify.sh and run it. You have successfully utilized Arithmetic, Relational, Boolean, and File operators in a single workflow.

12. Practice Exercises

  1. 1. Differentiate the operational use of the = operator versus the -eq operator in POSIX shell scripting.
  1. 2. Explain the catastrophic failure that occurs when attempting to use the > symbol to determine if integer A is greater than integer B within a script.

13. MCQs with Answers

Question 1

When utilizing the legacy expr utility to perform mathematical multiplication (e.g., 5 multiplied by 5), which syntax is required to prevent the shell from misinterpreting the asterisk as a wildcard?

Question 2

An automation script must append data to an existing server log. Which File Test Operator should be utilized to mathematically verify that the script has the required Linux permissions to alter the file?

14. Interview Questions

  • Q: A junior engineer writes the syntax [ $AGE>18 ] to verify if a user is an adult. Explain why this syntax is invalid in standard sh scripting, and describe the exact file-system anomaly this typo will silently generate.
  • Q: Walk me through the structural requirement of the -z String Operator. In what specific security or validation scenario is testing for a "Zero-length string" absolutely mandatory?
  • Q: Explain the necessity of wrapping variables in double quotes during string comparisons (e.g., [ "$INPUT" = "deploy" ]). What specific error is prevented by this formatting?

15. FAQs

Q: Can Shell scripts do decimal math? (Like 5.5 + 2.1) A: Natively, no. Standard sh and expr only understand whole integers. If you need decimal (floating-point) precision, you must pipe your math equation into an external Linux utility called bc (Basic Calculator).

16. Summary

In Chapter 4, we equipped our scripts with the ability to evaluate and calculate. We overcame the shell's text-only limitation by leveraging the expr command to process foundational integer arithmetic. We drew a strict, uncompromising line between Numeric Relational Operators (-eq, -gt) and String Match Operators (=, !=), eliminating the catastrophic redirection errors caused by < and >. Finally, we deployed File Test Operators (-f, -d) alongside Boolean logic (-a, -o), granting our scripts the sensory capability to independently verify the physical status and permissions of the surrounding operating system.

17. Next Chapter Recommendation

Our operators can perform tests, but the results just vanish into the ether. We must capture those true/false answers and use them to alter the path of the script. Proceed to Chapter 5: Conditional Statements.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·