Files
cmkiss/cmjs/articles/bob/linux/bash-scripting-basics.md
T
2026-08-23 21:54:17 +02:00

1.6 KiB

title, date, description, draft
title date description draft
Bash Scripting Basics 2026-06-08 Write your first shell scripts to automate repetitive tasks on Linux and macOS. false

A shell script is a plain text file containing a sequence of commands. The shell reads and executes them in order — a simple but powerful form of automation.

Your first script

#!/usr/bin/env bash
# The shebang line above tells the OS which interpreter to use

echo "Hello, world!"

Save it as hello.sh, make it executable, and run it:

chmod +x hello.sh
./hello.sh

Variables

Lorem ipsum dolor sit amet, consectetur adipiscing elit:

NAME="Bob"
echo "Hello, $NAME"

# Command substitution
TODAY=$(date +%Y-%m-%d)
echo "Today is $TODAY"

Conditionals and loops

# If / else
if [ -f "/etc/hosts" ]; then
    echo "hosts file exists"
else
    echo "hosts file missing"
fi

# For loop over files
for file in *.log; do
    echo "Processing $file"
    gzip "$file"
done

# While loop
COUNT=0
while [ $COUNT -lt 5 ]; do
    echo "Count: $COUNT"
    COUNT=$((COUNT + 1))
done

Functions

Ut enim ad minim veniam, quis nostrud exercitation:

backup() {
    local src="$1"
    local dst="$2"
    cp -r "$src" "$dst/$(basename $src)-$(date +%Y%m%d)"
    echo "Backed up $src to $dst"
}

backup /etc/nginx /var/backups

Practical tips

  • Always quote variables: "$VAR" not $VAR
  • Use set -e to exit on error
  • Use set -u to catch undefined variables
  • Prefer [[ ]] over [ ] for conditionals in bash

Automate anything you do more than twice. Your future self will thank you.