← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 11 of 12

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:

  1. Portability
Syntax
bash
#!/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

bash
#!/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[@]}"
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
  1. Using Bash-only features such as [[ ]] or arrays with #!/bin/sh.
  2. Assuming commands and options are the same across Linux and macOS.
  3. Hard-coding the path to bash, when #!/usr/bin/env bash is more portable.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.