Conquering Complexity: A Guide to Conditional Logic in Shell Scripting
Photo by Stanley Dai

Conquering Complexity: A Guide to Conditional Logic in Shell Scripting


Conditional logic is the backbone of powerful shell scripts. It allows your scripts to make decisions and execute code based on specific circumstances, transforming them from static tools to dynamic. This guide equips you with the knowledge to use conditional logic effectively in your shell scripting endeavors.

The Mighty If Statement

The if statement forms the foundation of conditional logic. It evaluates a condition and executes a block of code if that condition is true. and if block close using fi this is a common pattern. In condition alteast one space need between the brackets and your statement as well as value on each side.

Basic Structure:

if [ condition ]; 
then
  # Commands to execute if condition is true
fi        

Example:

if [ "a" = "a" ]; 
then
  echo "True"
else
  echo "False"
fi        

Expanding Your Options: If-Else and If-Elif-Else

The if-else statement allows you to execute different code blocks based on whether the condition is true or false.

if [ condition ]; 
then
  # Commands to execute if condition is true
else
  # Commands to execute if condition is false
fi        

For more complex scenarios, you can employ the if-elif-else structure to chain multiple conditions.

if [ condition1 ]; 
then
  # Commands to execute if condition1 is true
elif [ condition2 ]; 
then
  # Commands to execute if condition2 is true
else
  # Commands to execute if none of the conditions are true
fi        

Conditions: The Language of Decisions

Conditional statements rely on conditions to make judgements. Here are some common condition types:

File Conditions: Check file existence, type, permissions etc. (e.g., -e file, -f file)

String Conditions: Evaluate string emptiness, equality etc. (e.g., -z string, string1 = string2)

Numeric Conditions: Compare numbers using operators like -eq (equal), -gt (greater than), etc.

Example: Checking a user's input

read name
if [ -z "$name" ]; 
then
  echo "No name entered"
else
  echo "Hello, $name!"
fi        

Logical Operators: Combining Conditions

Logical operators like && (AND) and || (OR) allow you to combine conditions for more intricate decision-making.

&&: Both conditions must be true for the code block to execute.

||: Only one condition needs to be true for the code block to execute.

Example: Checking a file and its permissions

if [ -f "$filepath" ] && [ -r "$filepath" ]; 
then
  echo "File exists and is readable"
fi        

Case Statements: Multi-Way Branching

For scenarios involving multiple potential matches, a case statement offers a cleaner approach. It compares a variable against various patterns and executes corresponding code blocks.

Example: Recognizing a chosen fruit

fruit="apple"
case "$fruit" in
  "apple")
    echo "You chose apple"
    ;;
  "banana")
    echo "You chose banana"
    ;;
  "cherry")
    echo "You chose cherry"
    ;;
  *)  # Default case for unmatched patterns
    echo "Unknown fruit"
    ;;
esac        

Putting it All Together: A Sample Script

This script demonstrates the power of conditional logic by combining various elements:

#!/bin/bash
# Get user input for number, name, filepath, and fruit
echo "Enter a number:"
read num
# Use conditional statements to handle the number
if [ "$num" -lt 0 ]; then
  echo "The number is negative"
elif [ "$num" -eq 0 ]; then
  echo "The number is zero"
else
  echo "The number is positive"
fi
# Check if a name was entered
echo "Enter your name:"
read name
if [ -z "$name" ]; then
  echo "No name entered"
else
  echo "Hello, $name!"
fi
# Check if a file exists
echo "Enter a file path:"
read filepath
if [ -f "$filepath" ]; then
  echo "File exists"
else
  echo "File does not exist"
fi
# Recognize chosen fruit using a case statement
echo "Enter a fruit (apple, banana, cherry):"
read fruit
case "$fruit" in
  "apple")
    echo "You chose apple"        

Extended Test Constructs

This evaluvator only work in bash and other supported language only. This is often preferred over [ condition ] due to its extended functionality and ease of use.

Basic Structure:

if [[ condition ]];         

To view or add a comment, sign in

More articles by Thejan Vithanage

Explore content categories