Przejdลบ do treล›ci

๐ŸŒ 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
# โœ… POSIX compliant
[ -f "$file" ] && echo "exists"

# โŒ Bashism
[[ -f "$file" ]] && echo "exists"

Prefer External Tools Over Built-ins

Many built-in features vary between shells:

1
2
3
4
5
# โœ… More portable
expr 2 + 3

# โŒ Less portable
echo $((2+3))

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