Portability
In this page:
Portability
Scripts meant to run across different systems should avoid Bash-only features (like arrays or [[ ]]) if they need to work under plain POSIX sh, and should avoid assuming GNU-specific flags that differ on macOS/BSD tools. Testing on the actual target systems, and using #!/usr/bin/env bash instead of a hardcoded path, both improve portability. Being explicit about which shell and tool versions a script depends on prevents "works on my machine" surprises.
Note: If a script only uses POSIX features, give it a .sh extension and a #!/bin/sh shebang to signal it doesn't need Bash specifically.
Example: Portability
#!/usr/bin/env bash
# Using env in the shebang finds bash wherever it's installed,
# which is more portable across different systems.
echo "Bash version: $BASH_VERSION"
echo "This script relies on Bash-specific features like arrays:"
arr=(1 2 3)
echo "${arr[@]}"
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments