Essential Comparison Operators in Shell Scripting
Shell scripts rely on comparison operators to evaluate conditions. These operators are primarily used with the [ ] test construct or the test command. They are categorized based on the data they evaluate: files, strings, and integers.
File Test Operators
These operators check the properties of a file or directory.
String Comparison Operators
Always quote variables in string comparisons to prevent word splitting or globbing issues.
For pattern matching within strings, use the =~ operator inside the [[ ]] construct.
url="https://example.com"
if [[ "$url" =~ "example" ]]; then
echo "Substring found."
fi
Integer Comparison Operators
These operators compare whole numbers. Do not use them for floating-point arithmetic.
Within double parentheses (( )), you can use standard arithmetic symbols (<, <=, >, >=, ==, !=).
if (( fileSize < 1024 )); then
echo "File is small."
fi
Combining Conditions
Logical operators -a (AND), -o (OR), and ! (NOT) can combine multiple tests within a single [ ] or test command. The && and || operators are also commonly used between separate test commands.
primary="yes"
secondary="no"
if [ "$primary" = "yes" -a "$secondary" = "no" ]; then
echo "Condition met."
fi
if [ ! -f "/tmp/lockfile" ]; then
echo "Lock file not present."
fi
The test Command
The test command is functionally equivalent to the [ ] construct. The operators listed above work identically with it.
if test -d "$HOME/downloads"; then
echo "Downloads directory exists."
fi
Parameter and Variable Manipulation
Bash provides powerful variable substitution and manipulation features.
Practical Example: Argument Handling
This script demonstrates checking the number of command-line arguments and providing a default value.
#!/bin/bash
# Set default port
connection_port=8080
# Check if at least one argument was provided
if [ $# -ge 1 ]; then
connection_port=$1
fi
echo "Connecting to service on port: $connection_port"
# Command to connect would follow...