Effective String Handling and Conditional Logic in Bash
In Bash environments, variables are inherently treated as text sequences. This behavior implies that numerical values are processed as strings during comparison operations unless explicitly arithmetic evaluation is invoked. Understanding how to validate string content and length is cirtical for robust script development.
Comparison Operators
Standard test conditions allow for evaluating equality and inequality between two operands.
str1 = str2orstr1 == str2: Returns true if the content matches.str1 != str2: Returns true if the content differs.
Length verification relies on specific flags:
-z str: Evaluates to true if the string length is zero.-n str: Evaluates to true if the string length is non-zero. Note that enclosing the variable in double quotes is essential to prevent syntax errors when the variable is unset.
Validation Examples
Checking equality involves passing arguments to the test command or using bracket syntax.
# Verify matching text
[ "alpha" = "beta" ]
echo $? # Outputs 1 (False)
[ "alpha" != "beta" ]
echo $? # Outputs 0 (True)
# Numeric values treated as text
val_a=100
val_b=200
[ "$val_a" = "$val_b" ]
echo $? # Outputs 1 (False)
Handling empty states requires careful quoting to avoid word splitting issues.
# Define a variable
message="hello"
[ -z "$message" ]
echo $? # Outputs 1 (False, not empty)
# Unset variable
unset config_val
[ -n "$config_val" ]
echo $? # Outputs 1 (False, is empty)
[ -n $config_val ]
# Without quotes, this might behave unexpectedly depending on shell options
Practical Implementation
The following script demonstrates a basic authentication flow using string comparisons. It captures user enput and validates it against expected values.
#!/bin/bash
# Script: auth_verify.sh
# Purpose: Validate user credentials via string matching
# System details
SYS_RELEASE=$(cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2)
SYS_KERNEL=$(uname -r)
# Clear terminal
clear
# Display system info
echo -e "\e[36m${SYS_RELEASE}\e[0m"
echo -e "\e[36mKernel ${SYS_KERNEL}\e[0m"
echo "---------------------------------"
# Capture credentials
read -p "Enter username: " input_user
# Ensure username is provided
while [ -z "$input_user" ]; do
read -p "Enter username: " input_user
done
read -s -t 30 -p "Enter password: " input_pass
echo
echo "---------------------------------"
# Validate credentials
EXPECTED_USER="admin"
EXPECTED_PASS="secret123"
if [ "$input_user" = "$EXPECTED_USER" ] && [ "$input_pass" = "$EXPECTED_PASS" ]; then
echo "Authentication successful"
else
echo "Authentication failed"
fi
Execution results indicate success only when both strings match the predefined constants exactly.
$ ./auth_verify.sh
"Ubuntu 22.04 LTS"
Kernel 5.15.0-76-generic
---------------------------------
Enter username: admin
Enter password:
---------------------------------
Authentication successful