๐ Portability
Portable scripts work consistently across different Unix-like systems and shells. This section outlines best practices to achieve compatibility.
๐งญ Why Care About Portability?
Different systems ship with varying combinations of:
- Shells (sh, bash, zsh, dash)
- Utilities (grep, sed, find)
- Library versions and capabilities
Portable code avoids assumptions and uses widely supported constructs.
๐งช Best Practices
Stick to POSIX Compliance
POSIX defines minimal required features. Scripts using only POSIX constructs are highly portable.
Check compliance with tools like checkbashisms or shellcheck.
Example:
1 2 3 4 5 | |
Prefer External Tools Over Built-ins
Many built-in features vary between shells:
1 2 3 4 5 | |
Though arithmetic expansion is widely supported today.
๐งฐ Portable Alternatives Table
| Feature | Portable Way | Non-portable Example |
|---|---|---|
| String comparison | [ "$a" = "$b" ] |
[[ "$a" == "$b" ]] |
| Regex matching | case statement |
[[ "$a" =~ regex ]] |
| Arrays | Use separate files or delimited strings | Native arrays in bash/zsh |
| Arithmetic | expr, external calculator |
$(( )) |
| Process substitution | Avoid or simulate with temp files | <() |
๐งพ Summary
- Aim for POSIX compliance whenever possible.
- Avoid shell-specific extensions unless absolutely necessary.
- Test scripts in multiple environments.
- Document known dependencies clearly.
๐ Proceed to: Extended Parameters and Expansions