Back to Blog

Zsh Conditionals: if/else, File Tests & case Statements | Shell Scripting Tutorial #9

Sandy LaneSandy Lane

Video: Zsh Conditionals: if/else, File Tests & case Statements | Shell Scripting Tutorial #9 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Conditionals: if/else, File Tests & case Statements

Master decision-making in Zsh shell scripts using if/elif/else statements, string and numeric test operators, and file condition checks. This guide also introduces the case statement for efficient pattern matching, enabling you to write smarter and more flexible shell scripts.

Code

# Example: Grade Checker using if/elif/else and numeric tests
grade=85

if [[ $grade -ge 90 ]]; then
  echo "Excellent"
elif [[ $grade -ge 75 ]]; then
  echo "Good"
elif [[ $grade -ge 60 ]]; then
  echo "Pass"
else
  echo "Fail"
fi

# String tests: check if a variable is non-empty
name="Alice"
if [[ -n $name ]]; then
  echo "Name is set"
else
  echo "Name is empty"
fi

# File tests: check if a file exists and is readable
file="my_script.sh"
if [[ -e $file && -r $file ]]; then
  echo "$file exists and is readable"
else
  echo "$file is missing or not readable"
fi

# case statement for pattern matching
read -p "Enter a command (start/stop/status): " cmd
case $cmd in
  start)
    echo "Starting service..."
    ;;
  stop)
    echo "Stopping service..."
    ;;
  status)
    echo "Service status:"
    ;;
  *)
    echo "Unknown command"
    ;;
esac

Key Points

  • Use if/elif/else to execute different code blocks based on conditions in Zsh scripts.
  • String tests like -n and -z check if variables are non-empty or empty, while == and != compare strings.
  • Numeric tests such as -eq, -ne, -gt, and -lt compare integer values within [[ ]] brackets.
  • File tests (-e, -f, -d, -r, -w, -x) verify file existence, type, and permissions before acting on files.
  • The case statement simplifies handling multiple pattern matches, improving script readability and organization.