Portability
Portability is like writing a note in simple words that any classmate can read, instead of secret slang that only your best friend understands. Simple scripts run on more computers.
In this page:
Syntax
#!/bin/sh
# POSIX-only features, no Bash extensions
if [ condition ]; then
command
fi
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using Bash-only features such as
[[ ]]or arrays with#!/bin/sh. - Assuming commands and options are the same across Linux and macOS.
- Hard-coding the path to
bash, when#!/usr/bin/env bashis more portable.
🔒
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