0
0
Bash-scriptingComparisonBeginner · 3 min read

Bash vs sh: Key Differences and When to Use Each

The sh shell is a basic, POSIX-compliant shell mainly used for compatibility, while bash is a more powerful, feature-rich shell with extensions like arrays and improved scripting syntax. Scripts written for sh run on most Unix systems, but bash scripts offer more functionality and are common on Linux.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of bash and sh shells based on key factors.

Factorshbash
TypePOSIX-compliant basic shellBourne Again SHell, extended features
CompatibilityAvailable on almost all Unix systemsCommon on Linux, not always default on Unix
Scripting FeaturesLimited, basic syntaxAdvanced: arrays, functions, arithmetic, string manipulation
Interactive UseMinimal featuresCommand history, tab completion, prompt customization
Startup Files~/.profile~/.bashrc, ~/.bash_profile
PerformanceLightweight and fastSlightly heavier due to extra features
⚖️

Key Differences

sh is the original Unix shell designed for simple scripting and maximum portability. It follows the POSIX standard closely, which means scripts written for sh can run on almost any Unix-like system without modification. However, it lacks many modern conveniences and scripting enhancements.

bash is an improved shell built as a free replacement for sh. It adds many features like command history, tab completion, arrays, arithmetic expressions, and more readable scripting syntax. These features make bash popular for interactive use and complex scripts.

While bash can run most sh scripts, some bash-specific features will not work in sh. Also, on some systems, sh is a symbolic link to bash running in POSIX mode, limiting bash extensions.

⚖️

Code Comparison

This example shows a simple script that prints numbers 1 to 3 using a loop in bash.

bash
#!/bin/bash
for i in {1..3}; do
  echo "Number $i"
done
Output
Number 1 Number 2 Number 3
↔️

sh Equivalent

The same script written for sh uses a different loop syntax for compatibility.

sh
#!/bin/sh
i=1
while [ "$i" -le 3 ]; do
  echo "Number $i"
  i=$((i + 1))
done
Output
Number 1 Number 2 Number 3
🎯

When to Use Which

Choose sh when you need maximum portability across different Unix systems or when writing very simple scripts. It ensures your script runs almost anywhere without modification.

Choose bash when you want to use advanced scripting features, improved interactivity, or when working primarily on Linux systems where bash is standard. It makes scripting easier and more powerful.

Key Takeaways

Use sh for simple, portable scripts that run on any Unix system.
Use bash for advanced scripting features and better interactive use.
bash supports arrays, arithmetic, and improved syntax not in sh.
sh scripts are more limited but highly compatible.
On some systems, sh may link to bash in POSIX mode, restricting features.