Exemples de Bash/Shell Scripting
Exemples essentiels de scripting Bash pour l'administration système et l'automatisation
Key Facts
- Category
- Programming Languages
- Items
- 3
- Format Families
- sample
Sample Overview
Exemples essentiels de scripting Bash pour l'administration système et l'automatisation This sample set belongs to Programming Languages and can be used to test related workflows inside Elysia Tools.
💻 Bash Hello World bash
🟢 simple
⭐
Script de base Hello World en Bash et concepts fondamentaux de programmation shell
⏱️ 15 min
🏷️ bash, shell, scripting, linux, automation
Prerequisites:
Basic command line knowledge, Understanding of shell concepts
#!/bin/bash
# Bash Hello World Examples
# 1. Basic Hello World
echo "Hello, World!"
# 2. Hello World with variable
message="Hello, World!"
echo $message
# 3. Hello World with function
say_hello() {
echo "Hello, World!"
}
say_hello
# 4. Hello World with function parameters
greet() {
echo "Hello, $1!"
}
greet "World"
greet "Bash"
# 5. Hello World with read input
echo "Enter your name:"
read name
echo "Hello, $name!"
# 6. Hello World multiple times
for i in {1..5}
do
echo "Hello, World! $i"
done
# 7. Hello World with array
greetings=("Hello" "Bonjour" "Hola" "Ciao" "こんにちは")
for greeting in "${greetings[@]}"
do
echo "$greeting, World!"
done
# 8. Hello World with condition
current_hour=$(date +%H)
if [ $current_hour -lt 12 ]; then
echo "Good morning, World!"
elif [ $current_hour -lt 18 ]; then
echo "Good afternoon, World!"
else
echo "Good evening, World!"
fi
# 9. Hello World with colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${RED}Red${NC} Hello, ${GREEN}Green${NC} World!"
echo -e "${YELLOW}Yellow${NC} Bash Scripting!"
# 10. Hello World with logging
LOG_FILE="hello_world.log"
echo "Hello, World!" | tee -a "$LOG_FILE"
echo "Script executed at: $(date)" >> "$LOG_FILE"
echo "Log file created: $LOG_FILE"
# Basic data types and operations
# Strings
name="Bash Scripting"
echo "String variable: $name"
echo "String length: ${#name}"
# Numbers
num1=10
num2=5
echo "Numbers: $num1 and $num2"
echo "Sum: $((num1 + num2))"
echo "Difference: $((num1 - num2))"
echo "Product: $((num1 * num2))"
echo "Division: $((num1 / num2))"
echo "Modulus: $((num1 % num2))"
# Using expr for floating point (requires bc)
echo "Using bc for floating point:"
echo "10 / 3" | bc
echo "scale=2; 10 / 3" | bc
# Arrays
fruits=("apple" "banana" "cherry" "date")
echo "Fruits array: ${fruits[@]}"
echo "Number of fruits: ${#fruits[@]}"
echo "First fruit: ${fruits[0]}"
last_index=$((${#fruits[@]} - 1))
echo "Last fruit: ${fruits[$last_index]}"
echo "All fruits:"
for fruit in "${fruits[@]}"; do
echo " - $fruit"
done
# Associative arrays (Bash 4+)
declare -A person
person[name]="John Doe"
person[age]=30
person[city]="New York"
echo "Person information:"
for key in "${!person[@]}"; do
echo " $key: ${person[$key]}"
done
# Command line arguments
echo "Script name: $0"
echo "Number of arguments: $#"
echo "All arguments: $*"
echo "Arguments as array: ${@}"
if [ $# -gt 0 ]; then
echo "First argument: $1"
echo "Second argument: $2"
else
echo "No arguments provided. Usage: $0 <arg1> <arg2> ..."
fi
# Environment variables
echo "Current user: $USER"
echo "Home directory: $HOME"
echo "Current shell: $SHELL"
echo "Current path: $PWD"
echo "Hostname: $HOSTNAME"
# Control flow examples
# If-else
score=85
if [ $score -ge 90 ]; then
grade="A"
elif [ $score -ge 80 ]; then
grade="B"
elif [ $score -ge 70 ]; then
grade="C"
else
grade="F"
fi
echo "Score: $score, Grade: $grade"
# Case statement
echo "Enter a day of the week:"
read day
case $day in
Monday|monday|MONDAY)
echo "It's Monday - start of the work week!"
;;
Friday|friday|FRIDAY)
echo "It's Friday - almost weekend!"
;;
Saturday|saturday|SATURDAY|Sunday|sunday|SUNDAY)
echo "It's weekend! Time to relax!"
;;
*)
echo "It's a regular weekday."
;;
esac
# Loop examples
echo "For loop with range:"
for i in {1..10}; do
echo -n "$i "
done
echo
echo "While loop:"
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++))
done
echo "Until loop:"
counter=5
until [ $counter -le 0 ]; do
echo "Countdown: $counter"
((counter--))
done
# String operations
text="Hello, World!"
echo "Original: $text"
echo "Upper case: ${text^^}"
echo "Lower case: ${text,,}"
echo "Replace World with Bash: ${text/World/Bash}"
echo "Substring (first 5 chars): ${text:0:5}"
echo "Length: ${#text}"
# File operations
echo "File operations:"
# Create a file
echo "This is a test file." > test.txt
echo "Second line." >> test.txt
# Check if file exists
if [ -f "test.txt" ]; then
echo "test.txt exists"
echo "File size: $(wc -c < test.txt) bytes"
echo "Number of lines: $(wc -l < test.txt)"
fi
# Read file line by line
echo "Reading file line by line:"
while IFS= read -r line; do
echo "Line: $line"
done < test.txt
# Clean up
rm -f test.txt
# Function with return value
add() {
local result=$(( $1 + $2 ))
echo $result
}
sum=$(add 15 25)
echo "Function result: 15 + 25 = $sum"
# Function with multiple return values
get_user_info() {
echo "John Doe" # First return value
echo "30" # Second return value
echo "Developer" # Third return value
}
# Read multiple return values
read -r user_name user_age user_job <<< "$(get_user_info)"
echo "User: $user_name, Age: $user_age, Job: $user_job"
# Error handling
echo "Error handling examples:"
# Safe file operations
safe_file_read() {
local file="$1"
if [ ! -f "$file" ]; then
echo "Error: File '$file' does not exist" >&2
return 1
fi
echo "Reading file: $file"
cat "$file"
}
# Try to read a file that doesn't exist
safe_file_read "nonexistent.txt" || echo "Failed to read file"
# Exit codes
echo "Script will exit with code 0 (success)"
exit 0
💻 Administration Système Bash bash
🟡 intermediate
⭐⭐⭐⭐
Scripts pratiques Bash pour la surveillance système, la gestion de fichiers et l'administration de serveurs
⏱️ 25 min
🏷️ bash, sysadmin, monitoring, automation, devops
Prerequisites:
Bash basics, Linux/Unix system knowledge, Command line experience
#!/bin/bash
# Bash System Administration Examples
# 1. System Information Script
system_info() {
echo "=== System Information ==="
echo "Hostname: $(hostname)"
echo "Operating System: $(uname -s) $(uname -r)"
echo "Architecture: $(uname -m)"
echo "Uptime: $(uptime -p)"
echo "Current Date: $(date)"
echo ""
echo "=== Hardware Information ==="
echo "CPU Model: $(grep 'model name' /proc/cpuinfo | head -1 | cut -d: -f2 | xargs)"
echo "CPU Cores: $(nproc)"
echo "Memory Usage:"
free -h
echo ""
echo "=== Disk Usage ==="
df -h
echo ""
echo "=== Network Interfaces ==="
ip addr show | grep -E '^[0-9]+:' | while read line; do
interface=$(echo $line | cut -d: -f2 | xargs)
echo "Interface: $interface"
ip addr show "$interface" | grep 'inet ' | head -1
done
}
# 2. Process Monitoring Script
monitor_processes() {
echo "=== Process Monitoring ==="
echo "Top 10 CPU-consuming processes:"
ps aux --sort=-%cpu | head -11
echo ""
echo "Top 10 Memory-consuming processes:"
ps aux --sort=-%mem | head -11
echo ""
echo "System Load Average:"
uptime | awk -F'load average:' '{print $2}'
echo ""
echo "Running services:"
systemctl list-units --type=service --state=running | head -10
}
# 3. Log File Monitor
monitor_logs() {
LOG_DIR="/var/log"
LOG_FILES=("auth.log" "syslog" "kern.log" "messages")
echo "=== Log File Analysis ==="
for logfile in "${LOG_FILES[@]}"; do
if [ -f "$LOG_DIR/$logfile" ]; then
echo "--- $logfile ---"
echo "Size: $(du -h "$LOG_DIR/$logfile" | cut -f1)"
echo "Last modified: $(stat -c %y "$LOG_DIR/$logfile")"
echo "Recent entries (last 5):"
tail -5 "$LOG_DIR/$logfile" 2>/dev/null | grep -v '^$' | head -5
echo ""
fi
done
# Check for error patterns in logs
echo "=== Recent Error Patterns ==="
for logfile in "${LOG_FILES[@]}"; do
if [ -f "$LOG_DIR/$logfile" ]; then
error_count=$(grep -c -i "error|fail|critical" "$LOG_DIR/$logfile" 2>/dev/null || echo 0)
if [ $error_count -gt 0 ]; then
echo "$logfile: $error_count error/fail entries found"
fi
fi
done
}
# 4. Backup Script with Rotation
create_backup() {
SOURCE_DIR="$1"
BACKUP_DIR="$2"
DAYS_TO_KEEP=7
if [ -z "$SOURCE_DIR" ] || [ -z "$BACKUP_DIR" ]; then
echo "Usage: $0 <source_directory> <backup_directory>"
return 1
fi
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Create timestamp
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/backup_$TIMESTAMP.tar.gz"
echo "Creating backup of $SOURCE_DIR..."
# Create backup
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"
if [ $? -eq 0 ]; then
echo "Backup created successfully: $BACKUP_FILE"
echo "Backup size: $(du -h "$BACKUP_FILE" | cut -f1)"
else
echo "Backup failed!"
return 1
fi
# Remove old backups
echo "Removing backups older than $DAYS_TO_KEEP days..."
find "$BACKUP_DIR" -name "backup_*.tar.gz" -mtime +$DAYS_TO_KEEP -delete
echo "Backup rotation completed."
echo "Current backups:"
ls -lh "$BACKUP_DIR"/backup_*.tar.gz 2>/dev/null || echo "No backups found"
}
# 5. Service Management Script
manage_service() {
local service="$1"
local action="$2"
if [ -z "$service" ] || [ -z "$action" ]; then
echo "Usage: $0 <service_name> <start|stop|restart|status|enable|disable>"
return 1
fi
echo "Managing service: $service"
case $action in
start|stop|restart|status)
echo "Executing: systemctl $action $service"
systemctl "$action" "$service"
;;
enable|disable)
echo "Executing: systemctl $action $service"
systemctl "$action" "$service"
;;
*)
echo "Invalid action: $action"
echo "Valid actions: start, stop, restart, status, enable, disable"
return 1
;;
esac
if [ $? -eq 0 ]; then
echo "Service $action completed successfully"
else
echo "Service $action failed"
return 1
fi
}
# 6. File System Cleanup Script
cleanup_system() {
echo "=== System Cleanup ==="
# Clear package cache (Debian/Ubuntu)
if command -v apt &>/dev/null; then
echo "Cleaning APT cache..."
apt-get clean
echo "Removing old packages..."
apt-get autoremove -y
fi
# Clear package cache (RHEL/CentOS)
if command -v yum &>/dev/null; then
echo "Cleaning YUM cache..."
yum clean all
fi
# Clear temporary files
echo "Cleaning temporary files..."
find /tmp -type f -atime +7 -delete 2>/dev/null || true
# Clear user cache
echo "Cleaning user cache files..."
find /home -name ".cache" -type d -exec find {} -type f -atime +30 -delete \; 2>/dev/null || true
# Clear system logs (keep last 7 days)
echo "Cleaning old system logs..."
find /var/log -name "*.log" -type f -mtime +7 -exec truncate -s 0 {} \; 2>/dev/null || true
# Clear journal logs
if command -v journalctl &>/dev/null; then
echo "Cleaning journal logs..."
journalctl --vacuum-time=7d
fi
# Show disk space after cleanup
echo "Disk space after cleanup:"
df -h /
}
# 7. User and Group Management
manage_user() {
local action="$1"
local username="$2"
case $action in
"create")
if [ -z "$username" ]; then
echo "Usage: $0 create <username>"
return 1
fi
echo "Creating user: $username"
useradd -m -s /bin/bash "$username"
echo "Setting password for $username"
passwd "$username"
;;
"delete")
if [ -z "$username" ]; then
echo "Usage: $0 delete <username>"
return 1
fi
echo "Deleting user: $username"
userdel -r "$username"
;;
"list")
echo "System users:"
cat /etc/passwd | cut -d: -f1 | sort
;;
*)
echo "Usage: $0 <create|delete|list> [username]"
return 1
;;
esac
}
# 8. Network Monitoring Script
monitor_network() {
echo "=== Network Monitoring ==="
# Show active connections
echo "Active network connections:"
netstat -tuln | grep LISTEN
echo ""
echo "Network interfaces:"
ip addr show
echo ""
echo "Network statistics:"
cat /proc/net/dev
echo ""
echo "Routing table:"
ip route show
echo ""
echo "DNS servers:"
cat /etc/resolv.conf
# Test connectivity
echo ""
echo "Connectivity test:"
if ping -c 1 8.8.8.8 &>/dev/null; then
echo "✓ Internet connectivity OK"
else
echo "✗ Internet connectivity FAILED"
fi
}
# 9. Security Audit Script
security_audit() {
echo "=== Security Audit ==="
# Check for sudo users
echo "Users with sudo privileges:"
grep -E "sudo|wheel" /etc/group
echo ""
echo "Recent login attempts:"
last -n 10
echo ""
echo "Failed login attempts:"
grep "Failed password" /var/log/auth.log 2>/dev/null | tail -10 || \
grep "authentication failure" /var/log/secure 2>/dev/null | tail -10 || echo "No failed login attempts found"
echo ""
echo "Open ports:"
netstat -tuln | grep LISTEN
echo ""
echo "SSH configuration:"
if [ -f /etc/ssh/sshd_config ]; then
echo "Root login: $(grep -i "^PermitRootLogin" /etc/ssh/sshd_config || echo "Not configured")"
echo "Password authentication: $(grep -i "^PasswordAuthentication" /etc/ssh/sshd_config || echo "Not configured")"
echo "Port: $(grep -i "^Port" /etc/ssh/sshd_config || echo "Default (22)")"
fi
# Check file permissions
echo ""
echo "Important file permissions:"
echo "/etc/passwd: $(ls -l /etc/passwd | cut -d' ' -f1)"
echo "/etc/shadow: $(ls -l /etc/shadow | cut -d' ' -f1)"
echo "/etc/sudoers: $(ls -l /etc/sudoers | cut -d' ' -f1)"
}
# 10. Automated Updates Script
system_update() {
echo "=== System Update ==="
# Check update method based on distribution
if [ -f /etc/debian_version ]; then
# Debian/Ubuntu
echo "Detected Debian-based system"
echo "Updating package list..."
apt-get update
echo "Checking for available updates..."
apt list --upgradable 2>/dev/null | grep -v "WARNING" | wc -l
echo "Upgrading packages..."
DEBIAN_FRONTEND=noninteractive apt-get upgrade -y
echo "Installing security updates..."
DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade -y
elif [ -f /etc/redhat-release ]; then
# RHEL/CentOS/Fedora
echo "Detected Red Hat-based system"
echo "Updating packages..."
yum update -y
echo "Installing security updates..."
yum update --security -y
else
echo "Unsupported distribution for automatic updates"
return 1
fi
echo "Update completed successfully"
}
# Main script execution
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
case "${1:-help}" in
"info")
system_info
;;
"monitor")
monitor_processes
;;
"logs")
monitor_logs
;;
"backup")
create_backup "${2:-}" "${3:-}"
;;
"service")
manage_service "${2:-}" "${3:-}"
;;
"cleanup")
cleanup_system
;;
"user")
manage_user "${2:-}" "${3:-}"
;;
"network")
monitor_network
;;
"security")
security_audit
;;
"update")
system_update
;;
"help"|*)
echo "System Administration Script"
echo "Usage: $0 <command> [options]"
echo ""
echo "Commands:"
echo " info - Show system information"
echo " monitor - Monitor processes and system load"
echo " logs - Analyze log files"
echo " backup <source> <dest> - Create backup with rotation"
echo " service <name> <action> - Manage systemd services"
echo " cleanup - Clean system temporary files"
echo " user <action> [name] - Manage users (create/delete/list)"
echo " network - Monitor network status"
echo " security - Perform security audit"
echo " update - Update system packages"
echo " help - Show this help"
;;
esac
fi
💻 Automatisation DevOps Bash bash
🔴 complex
⭐⭐⭐⭐⭐
Scripts avancés Bash pour CI/CD, l'automatisation de déploiement et les workflows DevOps
⏱️ 40 min
🏷️ bash, devops, cicd, docker, automation, infrastructure
Prerequisites:
Advanced Bash, DevOps concepts, Docker knowledge, CI/CD understanding
#!/bin/bash
# Bash DevOps and Automation Examples
# 1. Docker Container Management
docker_management() {
local action="${1:-list}"
case $action in
"list")
echo "=== Docker Containers ==="
docker ps -a
echo ""
echo "=== Docker Images ==="
docker images
echo ""
echo "=== Docker Volumes ==="
docker volume ls
;;
"stats")
echo "=== Container Resource Usage ==="
docker stats --no-stream
;;
"cleanup")
echo "=== Docker Cleanup ==="
echo "Removing stopped containers..."
docker container prune -f
echo "Removing unused images..."
docker image prune -f
echo "Removing unused volumes..."
docker volume prune -f
;;
"build")
local image_name="${2:-myapp}"
local dockerfile_path="${3:-.}"
echo "Building Docker image: $image_name"
docker build -t "$image_name" "$dockerfile_path"
if [ $? -eq 0 ]; then
echo "✓ Docker image built successfully"
docker images | grep "$image_name"
else
echo "✗ Docker build failed"
return 1
fi
;;
*)
echo "Usage: $0 <list|stats|cleanup|build> [image_name] [dockerfile_path]"
return 1
;;
esac
}
# 2. Git Automation Script
git_automation() {
local action="${1:-status}"
case $action in
"status")
echo "=== Git Repository Status ==="
echo "Current branch: $(git branch --show-current)"
echo "Remote: $(git remote get-url origin 2>/dev/null || echo "No remote")"
echo ""
echo "Changes to be committed:"
git diff --cached --stat
echo ""
echo "Changes not staged:"
git diff --stat
echo ""
echo "Untracked files:"
git ls-files --others --exclude-standard
;;
"auto-commit")
local commit_message="${2:-Auto-commit $(date)}"
echo "=== Auto Commit Process ==="
# Add all changes
echo "Adding all changes..."
git add .
# Check if there are changes to commit
if git diff --cached --quiet; then
echo "No changes to commit"
return 0
fi
# Commit changes
echo "Committing changes..."
git commit -m "$commit_message"
# Push to remote if exists
if git remote get-url origin &>/dev/null; then
echo "Pushing to remote..."
git push
fi
echo "✓ Auto-commit completed"
;;
"branch-cleanup")
echo "=== Branch Cleanup ==="
# Fetch latest from remote
git fetch --prune
# List merged branches
echo "Merged branches (excluding main/master):"
git branch --merged | grep -v "\*" | grep -v "main\|master" | while read branch; do
echo " $branch"
done
# Ask for confirmation
read -p "Delete merged branches? (y/N): " confirm
if [[ $confirm =~ ^[Yy]$ ]]; then
git branch --merged | grep -v "\*" | grep -v "main\|master" | xargs -r git branch -d
echo "✓ Merged branches deleted"
fi
;;
"release")
local version="${2:-v$(date +%Y%m%d)}"
echo "=== Creating Release: $version ==="
# Create and push tag
git tag -a "$version" -m "Release $version"
git push origin "$version"
echo "✓ Release tag $version created and pushed"
;;
*)
echo "Usage: $0 <status|auto-commit|branch-cleanup|release> [options]"
return 1
;;
esac
}
# 3. Deployment Script
deploy_application() {
local app_name="${1:-myapp}"
local environment="${2:-staging}"
local version="${3:-latest}"
echo "=== Deploying $app_name to $environment ==="
echo "Version: $version"
echo "Deployment started at: $(date)"
# Pre-deployment checks
echo "Running pre-deployment checks..."
# Check if required tools are available
local required_tools=("docker" "git" "curl")
for tool in "${required_tools[@]}"; do
if ! command -v "$tool" &>/dev/null; then
echo "✗ Required tool not found: $tool"
return 1
fi
done
echo "✓ All required tools are available"
# Check if Docker is running
if ! docker info &>/dev/null; then
echo "✗ Docker is not running"
return 1
fi
echo "✓ Docker is running"
# Stop existing container if exists
echo "Stopping existing container..."
docker stop "$app_name" 2>/dev/null || true
docker rm "$app_name" 2>/dev/null || true
# Pull latest image
echo "Pulling Docker image: $app_name:$version"
docker pull "$app_name:$version"
if [ $? -ne 0 ]; then
echo "✗ Failed to pull Docker image"
return 1
fi
# Start new container
echo "Starting new container..."
docker run -d \
--name "$app_name" \
--restart unless-stopped \
-p 8080:8080 \
-e "ENVIRONMENT=$environment" \
-e "VERSION=$version" \
-v "/opt/$app_name/logs:/app/logs" \
"$app_name:$version"
if [ $? -ne 0 ]; then
echo "✗ Failed to start container"
return 1
fi
# Health check
echo "Performing health check..."
sleep 10
local health_check_url="http://localhost:8080/health"
local max_attempts=30
local attempt=1
while [ $attempt -le $max_attempts ]; do
if curl -f "$health_check_url" &>/dev/null; then
echo "✓ Health check passed"
break
fi
if [ $attempt -eq $max_attempts ]; then
echo "✗ Health check failed after $max_attempts attempts"
echo "Container logs:"
docker logs "$app_name"
return 1
fi
echo "Health check attempt $attempt/$max_attempts..."
sleep 2
((attempt++))
done
# Post-deployment
echo "Deployment completed successfully!"
echo "Container status:"
docker ps | grep "$app_name"
# Create deployment record
local deploy_log="/opt/$app_name/deployments.log"
mkdir -p "/opt/$app_name"
echo "$(date): Deployed $app_name version $version to $environment" >> "$deploy_log"
echo "Deployment logged to: $deploy_log"
}
# 4. CI/CD Pipeline Script
cicd_pipeline() {
local stage="${1:-build}"
local project_name="${2:-myproject}"
echo "=== CI/CD Pipeline: $stage ==="
echo "Project: $project_name"
echo "Stage: $stage"
echo "Timestamp: $(date)"
case $stage in
"build")
echo "=== Build Stage ==="
# Set environment variables
export CI=true
export BUILD_NUMBER="${BUILD_NUMBER:-$(date +%s)}"
export COMMIT_SHA="${COMMIT_SHA:-$(git rev-parse HEAD 2>/dev/null || echo 'unknown')}"
# Clean previous builds
echo "Cleaning previous builds..."
rm -rf dist/ build/ target/ || true
# Install dependencies
if [ -f "package.json" ]; then
echo "Installing Node.js dependencies..."
npm ci
elif [ -f "requirements.txt" ]; then
echo "Installing Python dependencies..."
pip install -r requirements.txt
elif [ -f "pom.xml" ]; then
echo "Building with Maven..."
mvn clean compile
elif [ -f "build.gradle" ]; then
echo "Building with Gradle..."
./gradlew build
fi
# Run tests
echo "Running tests..."
if [ -f "package.json" ] && npm run test --silent; then
echo "✓ Tests passed"
elif [ -f "requirements.txt" ] && python -m pytest; then
echo "✓ Tests passed"
elif [ -f "pom.xml" ] && mvn test; then
echo "✓ Tests passed"
else
echo "✗ Tests failed"
return 1
fi
# Build application
echo "Building application..."
if [ -f "package.json" ] && npm run build; then
echo "✓ Build completed"
elif [ -f "Dockerfile" ] && docker build -t "$project_name:$BUILD_NUMBER" .; then
echo "✓ Docker image built"
else
echo "✗ Build failed"
return 1
fi
echo "✓ Build stage completed successfully"
;;
"test")
echo "=== Test Stage ==="
# Run unit tests
echo "Running unit tests..."
if command -v pytest &>/dev/null; then
pytest --junitxml=test-results.xml
elif command -v npm &>/dev/null; then
npm test -- --coverage --reporter=junit
else
echo "No test runner found"
fi
# Run integration tests
echo "Running integration tests..."
if [ -d "tests/integration" ]; then
# Integration test logic here
echo "✓ Integration tests passed"
fi
# Security scan
echo "Running security scan..."
if command -v npm &>/dev/null && npm audit --audit-level=high; then
echo "✓ Security scan passed"
fi
echo "✓ Test stage completed successfully"
;;
"deploy")
local environment="${3:-staging}"
echo "=== Deploy Stage: $environment ==="
# Deploy based on environment
if [ "$environment" = "production" ]; then
echo "Deploying to production..."
deploy_application "$project_name" "production"
else
echo "Deploying to staging..."
deploy_application "$project_name" "staging"
fi
echo "✓ Deploy stage completed successfully"
;;
*)
echo "Usage: $0 <build|test|deploy> <project_name> [environment]"
return 1
;;
esac
}
# 5. Monitoring and Alerting Script
monitor_and_alert() {
local service="${1:-web}"
local url="${2:-http://localhost:8080/health}"
local alert_email="${3:[email protected]}"
local log_file="/var/log/monitor.log"
echo "=== Monitoring: $service ==="
echo "URL: $url"
echo "Alert email: $alert_email"
# Create log directory
mkdir -p "$(dirname "$log_file")"
# Check service health
echo "Checking service health..."
local response_code=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null)
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
if [ "$response_code" = "200" ]; then
echo "[$timestamp] ✓ $service is healthy (HTTP $response_code)" | tee -a "$log_file"
# Check response time
local response_time=$(curl -s -o /dev/null -w "%{time_total}" "$url")
echo "Response time: ${response_time}s"
# Alert if response time is too slow
if (( $(echo "$response_time > 2.0" | bc -l) )); then
echo "[$timestamp] ⚠ $service response time is slow: ${response_time}s" | tee -a "$log_file"
echo "Slow response alert sent to $alert_email"
fi
else
echo "[$timestamp] ✗ $service is unhealthy (HTTP $response_code)" | tee -a "$log_file"
# Send alert email (requires mail command)
if command -v mail &>/dev/null; then
echo "Service $service is down! HTTP response code: $response_code" | \
mail -s "ALERT: $service service down" "$alert_email"
fi
# Check if service needs restart
echo "Attempting to restart service..."
if command -v docker &>/dev/null; then
docker restart "$service" 2>/dev/null || systemctl restart "$service" 2>/dev/null || true
fi
fi
}
# Main script execution
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
case "${1:-help}" in
"docker")
docker_management "${2:-}" "${3:-}" "${4:-}"
;;
"git")
git_automation "${2:-}" "${3:-}" "${4:-}"
;;
"deploy")
deploy_application "${2:-}" "${3:-}" "${4:-}"
;;
"cicd")
cicd_pipeline "${2:-}" "${3:-}" "${4:-}"
;;
"monitor")
monitor_and_alert "${2:-}" "${3:-}" "${4:-}"
;;
"help"|*)
echo "DevOps Automation Script"
echo "Usage: $0 <command> [options]"
echo ""
echo "Commands:"
echo " docker <action> [options] - Docker container management"
echo " git <action> [options] - Git repository automation"
echo " deploy <app> <env> <version> - Application deployment"
echo " cicd <stage> <project> [env] - CI/CD pipeline automation"
echo " monitor <service> <url> - Service monitoring and alerting"
echo " help - Show this help"
;;
esac
fi