BudiBadu Logo
Samplebadu

Shell Script by Example: Conditionals

Bash 5.x

Implementing decision logic with this sample code demonstrating if-else statements using the test command, integer comparison operators like -ge and -lt, string equality checks, file existence tests, and case statements for pattern matching.

Code

#!/bin/bash

age=18

# Basic if-else with [ ... ] (test command)
if [ "$age" -ge 18 ]; then
    echo "Adult"
else
    echo "Minor"
fi

# String comparison
name="Alice"
if [ "$name" == "Alice" ]; then
    echo "Hello Alice"
fi

# File tests
if [ -f "/etc/passwd" ]; then
    echo "File exists"
fi

# Case statement
role="admin"
case "$role" in
    "admin")
        echo "Full Access"
        ;;
    "user")
        echo "Limited Access"
        ;;
    *)
        echo "Unknown Role"
        ;;
esac

Explanation

Conditionals in Bash rely on the exit status of commands, where exit code 0 indicates success and any non-zero code indicates failure. The if statement executes its block when the following command succeeds. The most common command used with if is test, represented by square brackets [ ... ]. Spaces around the brackets are mandatory because [ is actually a command, not syntax.

Bash supports different comparison operators depending on the data type. For integer comparisons, use operators like:

  • -eq for equality, -ne for not equal
  • -gt for greater than, -lt for less than
  • -ge for greater than or equal, -le for less than or equal

For strings, use == or = for equality, != for inequality, -z to check if empty, and -n to check if non-empty.

File test operators are powerful for checking filesystem conditions. Common operators include -f for regular file existence, -d for directory existence, -e for any path existence, -r for readable, -w for writable, and -x for executable. The case statement provides a cleaner alternative to multiple if-elif-else blocks when checking a variable against several patterns. Each pattern ends with ), and each block must terminate with ;;. The * pattern acts as a catch-all default.

Code Breakdown

6
[ "$age" -ge 18 ] tests if age is greater than or equal to 18.
14
== performs string equality comparison, not numeric.
19
-f tests if the path exists and is a regular file.
28
;; terminates each case block, required for proper syntax.