Comparing variables is a fundamental aspect of shell scripting, enabling conditional execution and decision-making within your scripts. This article demonstrates various techniques for comparing two variables in a shell script, covering numerical and string comparisons, handling different date formats, and practical examples.
Numerical Comparison
When comparing numerical variables, you can utilize the following operators:
-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
Example:
a=10
b=20
if [ "$a" -lt "$b" ]; then
echo "$a is less than $b"
else
echo "$a is not less than $b"
fi
String Comparison
For string comparisons, use these operators:
=
: equal to!=
: not equal to<
: less than (lexicographically)>
: greater than (lexicographically)-z
: string is empty-n
: string is not empty
Example:
str1="hello"
str2="world"
if [ "$str1" = "$str2" ]; then
echo "$str1 is equal to $str2"
else
echo "$str1 is not equal to $str2"
fi
Comparing Dates in Different Formats
When dealing with dates in various formats, direct comparison can be challenging. A common scenario involves comparing a date string with the current date. Here’s an example of comparing an SSL certificate’s expiration date with the current date:
#!/usr/bin/bash
function monthnumber {
month=$(echo ${1:0:3} | tr '[a-z]' '[A-Z]')
MONTHS="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"
tmp=${MONTHS%%$month*}
month=${#tmp}
monthnumber=$((month/3+1))
printf "%02dn" $monthnumber
}
TODAY=$(date "+%Y%m%d")
openssl s_client -connect github.com:443 2>/dev/null | openssl x509 -noout -enddate | cut -d'=' -f2 | sed 's/ *//g' > tmp.pem
cert_expiry_date=$(cat tmp.pem)
month_name=$(echo $cert_expiry_date | cut -d' ' -f1)
month_number=$(monthnumber $month_name)
cert_expiration_datestamp=$(echo $cert_expiry_date | awk "{printf "%d%02d%02d",$4,"${month_number}",$2}")
if [ "$cert_expiration_datestamp" -gt "$TODAY" ]; then
echo "Certificate is valid."
else
echo "Certificate has expired."
fi
rm tmp.pem
This script extracts the expiration date, converts the month name to a number, formats the date for comparison, and then compares it with the current date.
Conclusion
Comparing variables in shell scripts involves understanding different operators for numerical and string comparisons. When dealing with dates, it is crucial to handle various formats correctly to ensure accurate comparisons. The provided examples offer practical solutions for common comparison scenarios. By mastering these techniques, you can create more robust and powerful shell scripts.