Mikey’s Linux Field NotesAll topics

GUIDE 08 / AUTOMATION

Bash scripting

Build scripts with arguments, tests, loops, useful errors, and clear exit codes.

4 quick lessons · Examples to adapt to your server
In this guide
Start with a small scriptHandle parameters safelyUse tests and loopsRead input and diagnose failures

Commands use class paths and example filenames. Replace placeholders and inspect the target before making changes.

01

Start with a small script

The shebang selects Bash when you execute the file directly. Mark a script executable once; Git records its executable bit. Run syntax checks before execution.

COMMANDS & EXAMPLES
#!/bin/bash
# Purpose: Show a short report.
set -euo pipefail
printf "Server: %s\n" "$HOSTNAME"
date
Field note

set -e has context-dependent behavior; handle expected failures explicitly with if. -u rejects unset variables, and pipefail exposes failures in pipelines. These settings do not replace validation.

02

Handle parameters safely

${1:-} gives an empty fallback when argument 1 is absent. $# counts arguments. "$*" joins arguments into one string; "$@" preserves them as separate arguments.

COMMANDS & EXAMPLES
if [[ "${1:-}" == "-h" ]]; then
    printf "Usage: %s [note]\n" "$0"
    exit 0
fi
printf "%s\n" "$*"
Field note

Use "$@" when forwarding arguments to another command. Use "$*" when you intentionally want one joined note. Quote variable expansions to preserve spaces.

03

Use tests and loops

An if tests command success. Shell success is exit status 0; nonzero signals a failure or another condition defined by the program. Each loop needs do and done.

COMMANDS & EXAMPLES
for service in nginx sshd chronyd; do
    if systemctl is-active --quiet "$service"; then
        printf "OK: %s\n" "$service"
    else
        printf "FAIL: %s\n" "$service"
    fi
done
Field note

For arithmetic thresholds, validate input as numeric before comparing. Under set -e, prefer count=$((count + 1)) when counting failures; a standalone ((count++)) can return status 1 on its first increment.

04

Read input and diagnose failures

read -r preserves backslashes in typed input. bash -n checks syntax without running the script. bash -x executes the script and prints expanded commands to standard error.

COMMANDS & EXAMPLES
read -r -p "Note: " note
printf "%s\n" "$note"
bash -n ./store.sh
bash -x ./health-check.sh -q 2> trace.txt
Field note

A trace can reveal credentials or other sensitive values; inspect it before sharing. curl needs -f when a health check should fail on HTTP 4xx/5xx responses. -k disables TLS verification and is not a certificate-health test.