From c7c03a1da22932c73a31b7366a42617600ad9d19 Mon Sep 17 00:00:00 2001 From: Edson Brandi Date: Fri, 7 Nov 2025 22:00:05 +0000 Subject: [PATCH] Add Chapter 3 shell scripting examples Add comprehensive shell scripting examples covering fundamental concepts: - Basic scripts: hello.sh, vars.sh, status.sh - Control flow: case.sh, loops.sh - Functions and debugging: functions.sh, debug_demo.sh - File handling: list_files variants (POSIX, bash, exec approaches) - Practical utilities: backup.sh, organize_downloads.sh - Advanced topics: IFS handling, temporary file management These examples demonstrate portable shell scripting practices for FreeBSD driver development workflows. --- src/chapters/3/backup/backup.sh | 41 ++++++++++++ src/chapters/3/case/case.sh | 20 ++++++ src/chapters/3/debug_demo/debug_demo.sh | 11 ++++ src/chapters/3/functions/functions.sh | 40 ++++++++++++ src/chapters/3/hello/hello.sh | 9 +++ src/chapters/3/ifs/ifs.sh | 24 +++++++ src/chapters/3/list_files/list_files.sh | 16 +++++ .../3/list_files_bash/list_files_bash.sh | 14 ++++ .../3/list_files_exec/list_files_exec.sh | 12 ++++ .../3/list_files_posix/list_files_posix.sh | 23 +++++++ src/chapters/3/loops/loops.sh | 15 +++++ .../organize_downloads/organize_downloads.sh | 65 +++++++++++++++++++ src/chapters/3/status/status.sh | 11 ++++ src/chapters/3/tmp_demo/tmp_demo.sh | 15 +++++ src/chapters/3/vars/vars.sh | 13 ++++ 15 files changed, 329 insertions(+) create mode 100755 src/chapters/3/backup/backup.sh create mode 100755 src/chapters/3/case/case.sh create mode 100755 src/chapters/3/debug_demo/debug_demo.sh create mode 100755 src/chapters/3/functions/functions.sh create mode 100755 src/chapters/3/hello/hello.sh create mode 100755 src/chapters/3/ifs/ifs.sh create mode 100755 src/chapters/3/list_files/list_files.sh create mode 100755 src/chapters/3/list_files_bash/list_files_bash.sh create mode 100755 src/chapters/3/list_files_exec/list_files_exec.sh create mode 100755 src/chapters/3/list_files_posix/list_files_posix.sh create mode 100755 src/chapters/3/loops/loops.sh create mode 100755 src/chapters/3/organize_downloads/organize_downloads.sh create mode 100755 src/chapters/3/status/status.sh create mode 100755 src/chapters/3/tmp_demo/tmp_demo.sh create mode 100755 src/chapters/3/vars/vars.sh diff --git a/src/chapters/3/backup/backup.sh b/src/chapters/3/backup/backup.sh new file mode 100755 index 0000000..93e77e3 --- /dev/null +++ b/src/chapters/3/backup/backup.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# backup.sh create a timestamped tar archive of a directory +# Usage: ./backup.sh /path/to/source +# Notes: +# - Uses /bin/sh so it runs on a clean FreeBSD 14.x install. +# - Creates ~/backups if it does not exist. +# - Names the archive sourcebasename-YYYYMMDD-HHMMSS.tar.gz + +set -eu +# set -e: exit immediately if any command fails +# set -u: treat use of unset variables as an error + +# Validate input +if [ $# -ne 1 ]; then + echo "Usage: $0 /path/to/source" >&2 + exit 2 +fi + +src="$1" + +# Verify that source is a directory +if [ ! -d "$src" ]; then + echo "Error: $src is not a directory" >&2 + exit 3 +fi + +# Prepare destination directory +dest="${HOME}/backups" +mkdir -p "$dest" + +# Build a safe archive name using only the last path component +base="$(basename "$src")" +stamp="$(date +%Y%m%d-%H%M%S)" +archive="${dest}/${base}-${stamp}.tar.gz" + +# Create the archive +# tar(1) is in the base system. The flags mean: +# - c: create - z: gzip - f: file name - C: change to directory +tar -czf "$archive" -C "$(dirname "$src")" "$base" + +echo "Backup created: $archive" diff --git a/src/chapters/3/case/case.sh b/src/chapters/3/case/case.sh new file mode 100755 index 0000000..555e25b --- /dev/null +++ b/src/chapters/3/case/case.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# case.sh handle options with a case statement + +action="$1" # first command line argument + +case "$action" in + start) + echo "Starting service" + ;; + stop) + echo "Stopping service" + ;; + restart) + echo "Restarting service" + ;; + *) + echo "Usage: $0 {start|stop|restart}" >&2 + exit 2 + ;; +esac diff --git a/src/chapters/3/debug_demo/debug_demo.sh b/src/chapters/3/debug_demo/debug_demo.sh new file mode 100755 index 0000000..24461da --- /dev/null +++ b/src/chapters/3/debug_demo/debug_demo.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# debug_demo.sh show simple tracing + +# set -x comment to disable verbose trace: +set -x + +echo "Step 1" +ls /etc >/dev/null + +echo "Step 2" +date diff --git a/src/chapters/3/functions/functions.sh b/src/chapters/3/functions/functions.sh new file mode 100755 index 0000000..85db6b9 --- /dev/null +++ b/src/chapters/3/functions/functions.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# functions.sh - Demonstrates using functions and command-line arguments in a shell script. +# +# Usage: +# ./functions.sh NUM1 NUM2 +# Example: +# ./functions.sh 5 7 +# This will output: "[INFO] 5 + 7 = 12" + +# A simple function to print informational messages +say() { + # "$1" represents the first argument passed to the function + echo "[INFO] $1" +} + +# A function to sum two integers +sum() { + # "$1" and "$2" are the first and second arguments + local a="$1" + local b="$2" + + # Perform arithmetic expansion to add them + echo $((a + b)) +} + +# --- Main script execution starts here --- + +# Make sure the user provided two arguments +if [ $# -ne 2 ]; then + echo "Usage: $0 NUM1 NUM2" + exit 1 +fi + +say "Beginning work" + +# Call the sum() function with the provided arguments +result="$(sum "$1" "$2")" + +# Print the result in a nice format +say "$1 + $2 = $result" diff --git a/src/chapters/3/hello/hello.sh b/src/chapters/3/hello/hello.sh new file mode 100755 index 0000000..d5a7479 --- /dev/null +++ b/src/chapters/3/hello/hello.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# hello.sh a first shell script using FreeBSD's native /bin/sh +# Print a friendly message with the current date and the active user. + +# 'date' prints the current date and time +# 'whoami' prints the current user +echo "Hello from FreeBSD!" +echo "Date: $(date)" +echo "User: $(whoami)" diff --git a/src/chapters/3/ifs/ifs.sh b/src/chapters/3/ifs/ifs.sh new file mode 100755 index 0000000..6a5bc8e --- /dev/null +++ b/src/chapters/3/ifs/ifs.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# ifs.sh demonstrate file and numeric tests + +file="/etc/rc.conf" + +# -f tests if a regular file exists +if [ -f "$file" ]; then + echo "$file exists" +else + echo "$file does not exist" +fi + +num=5 +if [ "$num" -gt 3 ]; then + echo "$num is greater than 3" +fi + +# String tests +user="$(whoami)" +if [ "$user" = "root" ]; then + echo "You are root" +else + echo "You are $user" +fi diff --git a/src/chapters/3/list_files/list_files.sh b/src/chapters/3/list_files/list_files.sh new file mode 100755 index 0000000..7cc2218 --- /dev/null +++ b/src/chapters/3/list_files/list_files.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# list_files.sh - count files in home directory + +set -eu +cd "${HOME}" + +count=0 +while IFS= read -r f; do + fname=${f#./} + echo "File found: '$fname'" + count=$((count + 1)) +done << EOF +$(find . -maxdepth 1 -type f ! -name ".*" -print) +EOF + +echo "Total files found: $count" diff --git a/src/chapters/3/list_files_bash/list_files_bash.sh b/src/chapters/3/list_files_bash/list_files_bash.sh new file mode 100755 index 0000000..fae39ca --- /dev/null +++ b/src/chapters/3/list_files_bash/list_files_bash.sh @@ -0,0 +1,14 @@ +#!/usr/local/bin/bash +# list_files_bash.sh - correctly handle unusual filenames with bash + +set -eu +cd "${HOME}" + +count=0 +while IFS= read -r -d '' f; do + fname=${f#./} + echo "File found: '$fname'" + count=$((count + 1)) +done < <(find . -maxdepth 1 -type f ! -name ".*" -print0) + +echo "Total files found: $count" diff --git a/src/chapters/3/list_files_exec/list_files_exec.sh b/src/chapters/3/list_files_exec/list_files_exec.sh new file mode 100755 index 0000000..2968874 --- /dev/null +++ b/src/chapters/3/list_files_exec/list_files_exec.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# list_files_exec.sh - handle all filenames using find -exec + +set -eu +cd "${HOME}" + +find . -maxdepth 1 -type f ! -name ".*" -exec sh -c ' + for f; do + fname=${f#./} + printf "File found: '\''%s'\''\n" "$fname" + done +' sh {} + diff --git a/src/chapters/3/list_files_posix/list_files_posix.sh b/src/chapters/3/list_files_posix/list_files_posix.sh new file mode 100755 index 0000000..6e7eea0 --- /dev/null +++ b/src/chapters/3/list_files_posix/list_files_posix.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# list_files_posix.sh - POSIX-compliant file listing + +set -eu +cd "${HOME}" + +# Use a temporary file instead of a pipe +tmpfile=$(mktemp) +trap 'rm -f "$tmpfile"' EXIT + +# Store find results in temporary file +find . -maxdepth 1 -type f ! -name ".*" > "$tmpfile" + +count=0 +while IFS= read -r f; do + fname=${f#./} + [ -z "$fname" ] && continue + + echo "File found: '$fname'" + count=$((count + 1)) +done < "$tmpfile" + +echo "Total files found: $count" diff --git a/src/chapters/3/loops/loops.sh b/src/chapters/3/loops/loops.sh new file mode 100755 index 0000000..829295e --- /dev/null +++ b/src/chapters/3/loops/loops.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# loops.sh for and while loops in /bin/sh + +# A 'for' loop over pathnames. Always quote expansions to handle spaces safely. +for f in /etc/*.conf; do + echo "Found conf file: $f" +done + +# A 'while' loop to read lines from a file safely. +# The 'IFS=' and 'read -r' avoid trimming spaces and backslash escapes. +count=0 +while IFS= read -r line; do + count=$((count + 1)) +done < /etc/hosts +echo "The /etc/hosts file has $count lines" diff --git a/src/chapters/3/organize_downloads/organize_downloads.sh b/src/chapters/3/organize_downloads/organize_downloads.sh new file mode 100755 index 0000000..604f254 --- /dev/null +++ b/src/chapters/3/organize_downloads/organize_downloads.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# organize_downloads.sh - Tidy ~/Downloads by file extension +# +# Usage: +# ./organize_downloads.sh +# +# Creates subdirectories like Documents, Images, Audio, Video, Archives, Other +# and moves matched files into them safely. + +set -eu + +downloads="${HOME}/Downloads" + +# Create a temporary file to store the list of files +tmpfile=$(mktemp) + +# Remove temporary file when script exits (normal or error) +trap 'rm -f "$tmpfile"' EXIT + +# Ensure the Downloads directory exists +if [ ! -d "$downloads" ]; then + echo "Downloads directory not found at $downloads" >&2 + exit 1 +fi + +cd "$downloads" + +# Create target folders if missing +mkdir -p Documents Images Audio Video Archives Other + +# Find all regular files in current directory (non-recursive, excluding hidden files) +# -maxdepth 1: don't search in subdirectories +# -type f: only regular files (not directories or symlinks) +# ! -name ".*": exclude hidden files (those starting with a dot) +count=0 +find . -maxdepth 1 -type f ! -name ".*" > "$tmpfile" +while IFS= read -r f; do + # Strip leading "./" from path + fname=${f#./} + + # Skip if filename is empty (shouldn't happen, but safety check) + [ -z "$fname" ] && continue + + # Convert filename extension to lowercase for matching + lower=$(printf '%s' "$fname" | tr '[:upper:]' '[:lower:]') + + case "$lower" in + *.pdf|*.txt|*.md|*.doc|*.docx) dest="Documents" ;; + *.png|*.jpg|*.jpeg|*.gif|*.bmp) dest="Images" ;; + *.mp3|*.wav|*.flac) dest="Audio" ;; + *.mp4|*.mkv|*.mov|*.avi) dest="Video" ;; + *.zip|*.tar|*.gz|*.tgz|*.bz2) dest="Archives" ;; + *) dest="Other" ;; + esac + + echo "Moving '$fname' -> $dest/" + mv -n -- "$fname" "$dest/" # -n prevents overwriting existing files + count=$((count + 1)) # Increment the counter +done < "$tmpfile" # Feed the temporary file into the while loop + +if [ $count -eq 0 ]; then + echo "No files to organize." +else + echo "Done. Organized $count file(s)." +fi diff --git a/src/chapters/3/status/status.sh b/src/chapters/3/status/status.sh new file mode 100755 index 0000000..d1c7b0f --- /dev/null +++ b/src/chapters/3/status/status.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# status.sh show exit codes and conditional chaining + +# Try to list a directory that exists. 'ls' should return 0. +ls /etc && echo "Listing /etc succeeded" + +# Try something that fails. 'false' always returns nonzero. +false || echo "Previous command failed, so this message appears" + +# You can test the last status explicitly using $? +echo "Last status was $?" diff --git a/src/chapters/3/tmp_demo/tmp_demo.sh b/src/chapters/3/tmp_demo/tmp_demo.sh new file mode 100755 index 0000000..06c92aa --- /dev/null +++ b/src/chapters/3/tmp_demo/tmp_demo.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# tmp_demo.sh create and clean a temporary file safely + +set -eu + +tmpfile="$(mktemp -t myscript)" +# Arrange cleanup on exit for success or error +cleanup() { + [ -f "$tmpfile" ] && rm -f "$tmpfile" +} +trap cleanup EXIT + +echo "Temporary file is $tmpfile" +echo "Hello temp" > "$tmpfile" +echo "Contents: $(cat "$tmpfile")" diff --git a/src/chapters/3/vars/vars.sh b/src/chapters/3/vars/vars.sh new file mode 100755 index 0000000..bb96ad2 --- /dev/null +++ b/src/chapters/3/vars/vars.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# vars.sh demonstrate variables and proper quoting + +name="dev" +greeting="Welcome" +# Double quotes preserve spaces and expand variables. +echo "$greeting, $name" +# Single quotes prevent expansion. This prints the literal characters. +echo '$greeting, $name' + +# Command substitution captures output of a command. +today="$(date +%Y-%m-%d)" +echo "Today is $today"