Bash vs sh: Key Differences and When to Use Each
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.
| Factor | sh | bash |
|---|---|---|
| Type | POSIX-compliant basic shell | Bourne Again SHell, extended features |
| Compatibility | Available on almost all Unix systems | Common on Linux, not always default on Unix |
| Scripting Features | Limited, basic syntax | Advanced: arrays, functions, arithmetic, string manipulation |
| Interactive Use | Minimal features | Command history, tab completion, prompt customization |
| Startup Files | ~/.profile | ~/.bashrc, ~/.bash_profile |
| Performance | Lightweight and fast | Slightly 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.
#!/bin/bash for i in {1..3}; do echo "Number $i" done
sh Equivalent
The same script written for sh uses a different loop syntax for compatibility.
#!/bin/sh i=1 while [ "$i" -le 3 ]; do echo "Number $i" i=$((i + 1)) done
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
sh for simple, portable scripts that run on any Unix system.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.sh may link to bash in POSIX mode, restricting features.