Linux

Bash Scripting Guide: From Zero to Automation

ยท1 min read

Bash is the default shell on virtually every Linux distribution. Learning to write Bash scripts is one of the most valuable skills for any developer, system administrator, or power user. This guide takes you from the fundamentals to practical automation scripts that will save you hours of repetitive work.

Bash scripting allows you to combine multiple commands, add logic and flow control, handle errors gracefully, and automate complex workflows. Whether you need to batch rename files, deploy applications, or monitor system health, Bash is your Swiss Army knife on the command line.

Getting Started with Variables

Variables in Bash are untyped and created by simple assignment. Unlike many programming languages, there are no spaces around the equals sign. Variables are referenced with a dollar sign prefix. You can store strings, numbers, command outputs, and even arrays.

#!/bin/bash
NAME="GNU Today"
echo "Welcome to $NAME"

# Command substitution
FILES=$(ls -la | wc -l)
echo "You have $FILES files in this directory"

Conditionals and Loops

Bash supports if-else statements, case switches, for loops, while loops, and until loops. The test command ([ ]) is used for comparisons. Double brackets ([[ ]]) provide extended pattern matching and regex support.

for file in *.log; do
  if [[ -f "$file" ]]; then
    gzip "$file"
    echo "Compressed: $file"
  fi
done

Functions and Error Handling

Functions in Bash allow you to organize code into reusable blocks. Combined with exit codes and trap handlers, you can build robust scripts that handle errors gracefully and clean up temporary resources automatically.

cleanup() {
  rm -rf /tmp/build-*
  echo "Cleaned up temporary files"
}
trap cleanup EXIT

log_error() {
  echo "[ERROR] $1" >&2
  exit 1
}

Real-World Script: Automated Backup

This script creates timestamped backups of specified directories, compresses them, and cleans up backups older than 30 days. It's production-ready and can be scheduled via cron.

Related Guides