mirror of
https://github.com/ebrandi/FDD-book.git
synced 2026-12-06 00:23:30 +00:00
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.
This commit is contained in:
parent
712daf6c49
commit
c7c03a1da2
15 changed files with 329 additions and 0 deletions
41
src/chapters/3/backup/backup.sh
Executable file
41
src/chapters/3/backup/backup.sh
Executable file
|
|
@ -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"
|
||||
20
src/chapters/3/case/case.sh
Executable file
20
src/chapters/3/case/case.sh
Executable file
|
|
@ -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
|
||||
11
src/chapters/3/debug_demo/debug_demo.sh
Executable file
11
src/chapters/3/debug_demo/debug_demo.sh
Executable file
|
|
@ -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
|
||||
40
src/chapters/3/functions/functions.sh
Executable file
40
src/chapters/3/functions/functions.sh
Executable file
|
|
@ -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"
|
||||
9
src/chapters/3/hello/hello.sh
Executable file
9
src/chapters/3/hello/hello.sh
Executable file
|
|
@ -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)"
|
||||
24
src/chapters/3/ifs/ifs.sh
Executable file
24
src/chapters/3/ifs/ifs.sh
Executable file
|
|
@ -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
|
||||
16
src/chapters/3/list_files/list_files.sh
Executable file
16
src/chapters/3/list_files/list_files.sh
Executable file
|
|
@ -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"
|
||||
14
src/chapters/3/list_files_bash/list_files_bash.sh
Executable file
14
src/chapters/3/list_files_bash/list_files_bash.sh
Executable file
|
|
@ -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"
|
||||
12
src/chapters/3/list_files_exec/list_files_exec.sh
Executable file
12
src/chapters/3/list_files_exec/list_files_exec.sh
Executable file
|
|
@ -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 {} +
|
||||
23
src/chapters/3/list_files_posix/list_files_posix.sh
Executable file
23
src/chapters/3/list_files_posix/list_files_posix.sh
Executable file
|
|
@ -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"
|
||||
15
src/chapters/3/loops/loops.sh
Executable file
15
src/chapters/3/loops/loops.sh
Executable file
|
|
@ -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"
|
||||
65
src/chapters/3/organize_downloads/organize_downloads.sh
Executable file
65
src/chapters/3/organize_downloads/organize_downloads.sh
Executable file
|
|
@ -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
|
||||
11
src/chapters/3/status/status.sh
Executable file
11
src/chapters/3/status/status.sh
Executable file
|
|
@ -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 $?"
|
||||
15
src/chapters/3/tmp_demo/tmp_demo.sh
Executable file
15
src/chapters/3/tmp_demo/tmp_demo.sh
Executable file
|
|
@ -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")"
|
||||
13
src/chapters/3/vars/vars.sh
Executable file
13
src/chapters/3/vars/vars.sh
Executable file
|
|
@ -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"
|
||||
Loading…
Reference in a new issue