Bash Scripting Fundamentals

30 minLesson 6 of 16

Learning Objectives

  • Create and execute Bash scripts
  • Use variables, arrays, and mathematical operations
  • Write conditionals (if/elif/else) and loops (for/while)
  • Define and call functions with arguments

Your First Script

A Bash script is a file containing commands that execute sequentially.

Creating a Script

nano hello.sh
#!/bin/bash
# This is a comment
echo "Hello from NextGen Playground!"
echo "Current user: $USER"
echo "Current date: $(date)"

The #!/bin/bash (shebang) tells the system which interpreter to use.

Running a Script

# Method 1: Pass to bash directly
bash hello.sh
 
# Method 2: Make executable and run
chmod +x hello.sh
./hello.sh

Variables

#!/bin/bash
 
# Define variables (no spaces around =)
name="NextGen"
course="DevOps"
year=2025
 
# Use variables with $
echo "Welcome to $name $course training $year"
 
# Curly braces for clarity
echo "${name}Playground"
⚠️

No spaces around = when assigning variables. name = "value" will fail.

Command Substitution

Store command output in a variable:

# Modern syntax (preferred)
current_dir=$(pwd)
file_count=$(ls | wc -l)
 
# Legacy syntax (backticks)
hostname=`hostname`
 
echo "Directory: $current_dir"
echo "Files: $file_count"
echo "Host: $hostname"

Quoting Rules

name="DevOps"
 
# Double quotes: variables are expanded
echo "Learning $name"        # Output: Learning DevOps
 
# Single quotes: everything is literal
echo 'Learning $name'        # Output: Learning $name
 
# Backticks: command substitution (legacy)
echo "Date: `date`"          # Output: Date: Mon Jan 1 ...

Mathematical Operations

#!/bin/bash
 
# Using let
let "a = 5"
let "b = 3"
let "sum = a + b"
let "product = a * b"
let "power = a ** 2"
 
echo "Sum: $sum"         # 8
echo "Product: $product" # 15
echo "Power: $power"     # 25
 
# Using $(( )) syntax (preferred)
result=$((10 + 5))
echo "Result: $result"   # 15
 
# Increment
counter=0
((counter++))
echo "Counter: $counter" # 1

Arrays

#!/bin/bash
 
# Define an array
tools=("docker" "kubernetes" "terraform" "ansible")
 
# Access elements (0-indexed)
echo "First: ${tools[0]}"    # docker
echo "Third: ${tools[2]}"    # terraform
 
# All elements
echo "All: ${tools[*]}"
 
# Array length
echo "Count: ${#tools[*]}"   # 4
 
# Add an element
tools[4]="jenkins"
 
# Loop through array
for tool in "${tools[@]}"; do
    echo "- $tool"
done

Conditionals

if / then / fi

#!/bin/bash
 
name="DevOps"
 
if [ "$name" = "DevOps" ]; then
    echo "Welcome to the DevOps track!"
fi

if / else

#!/bin/bash
 
score=85
 
if [ $score -ge 70 ]; then
    echo "Passed! Score: $score"
else
    echo "Failed. Score: $score"
fi

if / elif / else

#!/bin/bash
 
grade=92
 
if [ $grade -ge 90 ]; then
    echo "Excellent!"
elif [ $grade -ge 70 ]; then
    echo "Good job!"
elif [ $grade -ge 50 ]; then
    echo "Needs improvement"
else
    echo "Failed"
fi

Comparison Operators

String comparisons:

OperatorMeaning
=Equal
!=Not equal
-zString is empty
-nString is not empty

Numeric comparisons:

OperatorMeaning
-eqEqual
-neNot equal
-gtGreater than
-ltLess than
-geGreater or equal
-leLess or equal

Combining conditions:

# AND (both must be true)
if [[ $age -ge 18 && $country == "CM" ]]; then
    echo "Eligible"
fi
 
# OR (at least one true)
if [[ $role == "admin" || $role == "devops" ]]; then
    echo "Access granted"
fi

Loops

For Loop

#!/bin/bash
 
# Loop through a list
for server in web1 web2 web3 db1; do
    echo "Checking $server..."
done
 
# Loop through a range
for i in {1..5}; do
    echo "Iteration $i"
done
 
# C-style for loop
for ((i=0; i<10; i++)); do
    echo "Count: $i"
done
 
# Loop through files
for file in *.txt; do
    echo "Processing: $file"
done

While Loop

#!/bin/bash
 
counter=0
 
while [ $counter -lt 5 ]; do
    echo "Counter: $counter"
    ((counter++))
done
 
echo "Done! Final value: $counter"

Using seq

# Generate a sequence
for i in $(seq 1 10); do
    echo "Number: $i"
done
 
# With step
for i in $(seq 0 2 10); do
    echo "Even: $i"
done

Functions

#!/bin/bash
 
# Define a function
greet() {
    echo "Hello, $1! Welcome to $2."
}
 
# Call with arguments
greet "Engineer" "NextGen Playground"
 
# Function with return value
check_service() {
    if systemctl is-active --quiet $1; then
        echo "$1 is running"
        return 0
    else
        echo "$1 is NOT running"
        return 1
    fi
}
 
check_service "nginx"

Function with Local Variables

calculate_disk() {
    local usage=$(df -h / | awk 'NR==2 {print $5}')
    echo "Disk usage: $usage"
}
 
calculate_disk

Practical Script: Server Health Check

#!/bin/bash
# health_check.sh - Basic server health monitor
 
echo "=== Server Health Check ==="
echo "Date: $(date)"
echo "Hostname: $(hostname)"
echo ""
 
# CPU load
echo "--- CPU Load ---"
uptime | awk -F'load average:' '{print $2}'
 
# Memory usage
echo ""
echo "--- Memory ---"
free -h | grep Mem | awk '{print "Used: "$3" / Total: "$2}'
 
# Disk usage
echo ""
echo "--- Disk ---"
df -h / | awk 'NR==2 {print "Used: "$3" / Total: "$2" ("$5" full)"}'
 
# Top 5 processes by CPU
echo ""
echo "--- Top Processes (CPU) ---"
ps aux --sort=-%cpu | head -6
 
echo ""
echo "=== Check Complete ==="

Make it executable and run:

chmod +x health_check.sh
./health_check.sh

Summary

  • Scripts start with #!/bin/bash and need execute permission
  • Variables: name="value", access with $name
  • Math: let or $(( )) syntax
  • Arrays: arr=("a" "b" "c"), access with ${arr[0]}
  • Conditionals: if [ condition ]; then ... fi
  • Loops: for, while with various iteration patterns
  • Functions: name() { ... }, arguments via $1, $2, etc.

Next Steps

In the next lesson, we'll cover process management and crontab — scheduling automated tasks is essential for DevOps operations.