incorporated section on shell portability

This commit is contained in:
johnholloway77 2025-11-04 14:53:47 -07:00
parent 1c7c50ef70
commit 98204d3d9f

View file

@ -2590,6 +2590,205 @@ 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