Update chapter-03.md to fix wrapping up section position

Adjusted the position of wrapping up section for the shell section.
This commit is contained in:
Edson Brandi 2025-11-04 23:10:37 +00:00 committed by GitHub
parent f9ba50bc19
commit b001b9aa28
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -2504,73 +2504,73 @@ date
This small utility sorts files in `~/Downloads` into subfolders by extension. It demonstrates loops, case, tests and safety checks.
```sh
#!/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
```
```sh
#!/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
```
### Hands-on Lab: three mini tasks
@ -2590,205 +2590,6 @@ All scripts should start with `#!/bin/sh`, contain comments explaining each step
- **Assuming the same environment under cron.** Always use full paths and redirect output to a log file.
- **Hardcoding temporary file names.** Use `mktemp` and `trap` to clean up.
- **Spaces around `=` in assignments.** `name=value` is correct. `name = value` is not.
### Shell Portability: Handling Edge Cases and bash vs sh
So far, we've written scripts using FreeBSD's native `/bin/sh` shell, which follows the POSIX standard. This makes our scripts portable across different UNIX systems. But as you explore shell scripting examples online or receive contributions from other developers, you'll encounter scripts written for **bash** that use features not available in POSIX sh.
Understanding the differences between bash and sh, and knowing how to handle edge cases like unusual filenames, will help you write robust scripts and decide when portability matters more than convenience.
#### The Problem: Filenames with Special Characters
UNIX allows filenames to contain almost any character except forward slash `/` (which separates directories) and the null character `\0`. This means a filename can legally contain spaces, newlines, tabs, or other surprising characters.
Let's create a file with a newline in its name to see how this affects our scripts:
```sh
% cd ~
% touch $'file_with\nnewline.txt'
% ls
file_with?newline.txt
```
The `?` appears because `ls` substitutes unprintable characters when displaying filenames. The actual filename contains:
```
file_with
newline.txt
```
Now let's see what happens when a script tries to process this file.
#### A Naive Approach That Breaks
Here's a simple script that lists files in your home directory:
```sh
#!/bin/sh
# list_files.sh - count files in home directory
set -eu
cd "${HOME}"
count=0
find . -maxdepth 1 -type f ! -name ".*" -print |
while IFS= read -r f; do
fname=${f#./}
echo "File found: '$fname'"
count=$((count + 1))
done
echo "Total files found: $count"
```
Running this script with our unusual filename produces incorrect results:
```sh
% ./list_files.sh
File found: 'file_with'
File found: 'newline.txt'
Total files found: 2
```
The script thinks one file is actually two files because `find -print` outputs one path per line, and our filename contains a newline character. The script breaks on a perfectly valid UNIX filename.
#### The bash Solution: Using Null Delimiters
One way to fix this is to use null characters (`\0`) as delimiters instead of newlines. Bash supports this with the `-d` option to the `read` command:
```sh
#!/usr/local/bin/bash
# list_files_bash.sh - correctly handle unusual filenames with bash
set -eu
cd "${HOME}"
count=0
find . -maxdepth 1 -type f ! -name ".*" -print0 |
while IFS= read -r -d '' f; do
fname=${f#./}
echo "File found: '$fname'"
count=$((count + 1))
done
echo "Total files found: $count"
```
Notice two changes:
1. **Shebang**: Changed to `#!/usr/local/bin/bash` (bash's location on FreeBSD after `pkg install bash`)
2. **find flag**: Changed from `-print` to `-print0` (outputs null-delimited paths)
3. **read option**: Added `-d ''` to tell `read` to use null as the delimiter
This version works correctly:
```sh
% ./list_files_bash.sh
File found: 'file_with
newline.txt'
Total files found: 1
```
The downside? **This script now requires bash**, which is not part of the FreeBSD base system. It creates a dependency.
#### The POSIX-Compliant Alternative
If portability matters more than handling every possible edge case, we can write a POSIX-compliant version that avoids bash-specific features:
```sh
#!/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"
```
This version:
- Works on any POSIX-compliant shell (no bash required)
- Uses a temporary file instead of a pipe to avoid subshell variable issues
- Cleans up automatically with `trap`
- Handles filenames with spaces and most special characters
The limitation? It still can't handle filenames with newlines correctly, because POSIX sh's `read` command has no way to use a different delimiter. For this version:
```sh
% ./list_files_posix.sh
File found: 'file_with'
File found: 'newline.txt'
Total files found: 2
```
#### Understanding the Trade-Off
This reveals an important decision point in shell scripting:
**Portability vs Edge Case Coverage**
| Approach | Pros | Cons |
| ---------------- | ----------------------------------- | ------------------------------------- |
| **POSIX sh** | Runs everywhere, no dependencies | Cannot handle filenames with newlines |
| **bash with -d** | Handles all valid filenames | Requires bash installation |
| **find -exec** | POSIX-compliant, handles everything | More complex syntax |
For most real-world scripting, the POSIX approach is sufficient. Filenames with newlines are extremely rare outside of contrived examples or security exploits. Files with spaces, unicode characters, and other printable characters work fine with the POSIX version.
#### When to Choose bash
Use bash when:
- You're writing personal tools where bash is guaranteed to be available
- You genuinely need to handle filenames with newlines (very rare)
- You need bash-specific features like arrays, extended regex, or advanced string manipulation
- The script is part of a project that already depends on bash
Use POSIX sh when:
- Writing system administration scripts that need to run on any FreeBSD system
- Contributing to FreeBSD base system scripts
- Maximum portability is required
- The script might run in rescue mode or minimal environments
#### A Third Option: find -exec
For completeness, here's a POSIX-compliant approach that handles all filenames correctly without requiring bash:
```sh
#!/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 {} +
```
This works because `find -exec` passes filenames as arguments, not through pipes or line-based reading. It's POSIX-compliant and handles every edge case, but the syntax is less intuitive for beginners.
#### Practical Advice
When writing shell scripts:
1. **Start with `/bin/sh`** - Begin with POSIX-compliant scripts
2. **Quote your variables** - Always use `"$var"` to handle spaces
3. **Test with unusual filenames** - Create test files with spaces in their names
4. **Document dependencies** - If you use bash, state it clearly in comments
5. **Accept reasonable limitations** - Don't sacrifice portability for edge cases you'll never encounter
The organize_downloads.sh script we wrote earlier uses the POSIX-compliant temporary file approach. It handles the vast majority of real-world filenames correctly while remaining portable across any FreeBSD system.
Remember: **the best script is one that works reliably in your target environment**. Don't add bash as a dependency for edge cases you'll never hit, but don't torture yourself with POSIX constraints if you're writing personal tools on a system where bash is already installed.
### Wrapping up
@ -2798,6 +2599,205 @@ But remember: you don't need to memorize every construct or command option. Part
That's exactly what we'll cover next. In the following section, you'll learn how to use FreeBSD's built-in documentation, the famous FreeBSD Handbook, and the community around the project. These resources will become your companions as you continue your journey into device driver development.
## Shell Portability: Handling Edge Cases and bash vs sh
So far, we've written scripts using FreeBSD's native `/bin/sh` shell, which follows the POSIX standard. This makes our scripts portable across different UNIX systems. But as you explore shell scripting examples online or receive contributions from other developers, you'll encounter scripts written for **bash** that use features not available in POSIX sh.
Understanding the differences between bash and sh, and knowing how to handle edge cases like unusual filenames, will help you write robust scripts and decide when portability matters more than convenience.
#### The Problem: Filenames with Special Characters
UNIX allows filenames to contain almost any character except forward slash `/` (which separates directories) and the null character `\0`. This means a filename can legally contain spaces, newlines, tabs, or other surprising characters.
Let's create a file with a newline in its name to see how this affects our scripts:
```sh
% cd ~
% touch $'file_with\nnewline.txt'
% ls
file_with?newline.txt
```
The `?` appears because `ls` substitutes unprintable characters when displaying filenames. The actual filename contains:
```
file_with
newline.txt
```
Now let's see what happens when a script tries to process this file.
#### A Naive Approach That Breaks
Here's a simple script that lists files in your home directory:
```sh
#!/bin/sh
# list_files.sh - count files in home directory
set -eu
cd "${HOME}"
count=0
find . -maxdepth 1 -type f ! -name ".*" -print |
while IFS= read -r f; do
fname=${f#./}
echo "File found: '$fname'"
count=$((count + 1))
done
echo "Total files found: $count"
```
Running this script with our unusual filename produces incorrect results:
```sh
% ./list_files.sh
File found: 'file_with'
File found: 'newline.txt'
Total files found: 2
```
The script thinks one file is actually two files because `find -print` outputs one path per line, and our filename contains a newline character. The script breaks on a perfectly valid UNIX filename.
#### The bash Solution: Using Null Delimiters
One way to fix this is to use null characters (`\0`) as delimiters instead of newlines. Bash supports this with the `-d` option to the `read` command:
```sh
#!/usr/local/bin/bash
# list_files_bash.sh - correctly handle unusual filenames with bash
set -eu
cd "${HOME}"
count=0
find . -maxdepth 1 -type f ! -name ".*" -print0 |
while IFS= read -r -d '' f; do
fname=${f#./}
echo "File found: '$fname'"
count=$((count + 1))
done
echo "Total files found: $count"
```
Notice two changes:
1. **Shebang**: Changed to `#!/usr/local/bin/bash` (bash's location on FreeBSD after `pkg install bash`)
2. **find flag**: Changed from `-print` to `-print0` (outputs null-delimited paths)
3. **read option**: Added `-d ''` to tell `read` to use null as the delimiter
This version works correctly:
```sh
% ./list_files_bash.sh
File found: 'file_with
newline.txt'
Total files found: 1
```
The downside? **This script now requires bash**, which is not part of the FreeBSD base system. It creates a dependency.
#### The POSIX-Compliant Alternative
If portability matters more than handling every possible edge case, we can write a POSIX-compliant version that avoids bash-specific features:
```sh
#!/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"
```
This version:
- Works on any POSIX-compliant shell (no bash required)
- Uses a temporary file instead of a pipe to avoid subshell variable issues
- Cleans up automatically with `trap`
- Handles filenames with spaces and most special characters
The limitation? It still can't handle filenames with newlines correctly, because POSIX sh's `read` command has no way to use a different delimiter. For this version:
```sh
% ./list_files_posix.sh
File found: 'file_with'
File found: 'newline.txt'
Total files found: 2
```
#### Understanding the Trade-Off
This reveals an important decision point in shell scripting:
**Portability vs Edge Case Coverage**
| Approach | Pros | Cons |
| ---------------- | ----------------------------------- | ------------------------------------- |
| **POSIX sh** | Runs everywhere, no dependencies | Cannot handle filenames with newlines |
| **bash with -d** | Handles all valid filenames | Requires bash installation |
| **find -exec** | POSIX-compliant, handles everything | More complex syntax |
For most real-world scripting, the POSIX approach is sufficient. Filenames with newlines are extremely rare outside of contrived examples or security exploits. Files with spaces, unicode characters, and other printable characters work fine with the POSIX version.
#### When to Choose bash
Use bash when:
- You're writing personal tools where bash is guaranteed to be available
- You genuinely need to handle filenames with newlines (very rare)
- You need bash-specific features like arrays, extended regex, or advanced string manipulation
- The script is part of a project that already depends on bash
Use POSIX sh when:
- Writing system administration scripts that need to run on any FreeBSD system
- Contributing to FreeBSD base system scripts
- Maximum portability is required
- The script might run in rescue mode or minimal environments
#### A Third Option: find -exec
For completeness, here's a POSIX-compliant approach that handles all filenames correctly without requiring bash:
```sh
#!/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 {} +
```
This works because `find -exec` passes filenames as arguments, not through pipes or line-based reading. It's POSIX-compliant and handles every edge case, but the syntax is less intuitive for beginners.
#### Practical Advice
When writing shell scripts:
1. **Start with `/bin/sh`** - Begin with POSIX-compliant scripts
2. **Quote your variables** - Always use `"$var"` to handle spaces
3. **Test with unusual filenames** - Create test files with spaces in their names
4. **Document dependencies** - If you use bash, state it clearly in comments
5. **Accept reasonable limitations** - Don't sacrifice portability for edge cases you'll never encounter
The organize_downloads.sh script we wrote earlier uses the POSIX-compliant temporary file approach. It handles the vast majority of real-world filenames correctly while remaining portable across any FreeBSD system.
Remember: **the best script is one that works reliably in your target environment**. Don't add bash as a dependency for edge cases you'll never hit, but don't torture yourself with POSIX constraints if you're writing personal tools on a system where bash is already installed.
## Seeking Help and Documentation in FreeBSD
No one, not even the most experienced developer, remembers every command, option, or system call. The real strength of a UNIX system like FreeBSD is that it ships with **excellent documentation** and has a supportive community that can help when you get stuck.
@ -3409,3 +3409,4 @@ These exercises are the **muscle memory** you'll need when we start programming.
The next chapter will introduce the **C programming language**, the language of the FreeBSD kernel. This is the tool you'll use to create device drivers. Don't worry if you've never programmed before, we'll build your understanding step by step, just as we did with UNIX in this chapter.
By combining your new UNIX literacy with C programming skills, you'll be ready to begin shaping the FreeBSD kernel itself.