Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Effective String Handling and Conditional Logic in Bash

Tech May 10 3

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 = str2 or str1 == 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
Tags: bash

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.