Bash vs sh: Key Differences and When to Use Each
sh shell is a basic, POSIX-compliant shell mainly used for simple scripts and maximum compatibility, while bash is an enhanced shell with more features like arrays, functions, and improved scripting syntax. Use bash for advanced scripting and interactive use, and sh when you need portability across different Unix systems.Quick Comparison
This table summarizes the main differences between bash and sh shells.
| Factor | sh | bash |
|---|---|---|
| Type | Basic POSIX shell | Enhanced Bourne Again Shell |
| Compatibility | Highly portable across Unix systems | Mostly compatible but with extensions |
| Features | Limited scripting features | Supports arrays, functions, arithmetic, and more |
| Interactive Use | Minimal interactive features | Rich interactive features like tab completion |
| Default Shell | Default on many Unix systems | Default on many Linux distributions |
| Script Syntax | Strict POSIX syntax | Extended syntax with more commands |
Key Differences
sh is the original Unix shell designed for simple scripting and maximum portability. It follows the POSIX standard strictly, which means scripts written for sh will run on almost any Unix-like system without modification. However, it lacks many modern conveniences.
bash stands for Bourne Again SHell and is a superset of sh. It adds many features like arrays, improved variable handling, arithmetic operations, and better interactive use such as command history and tab completion. This makes bash more powerful for writing complex scripts and for daily command line use.
While bash scripts often run fine under sh, scripts using bash-specific features will fail in sh. Therefore, choosing between them depends on whether you prioritize portability or advanced features.
Code Comparison
Here is 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 equivalent script in sh uses a different loop syntax because sh does not support brace expansion.
#!/bin/sh i=1 while [ "$i" -le 3 ]; do echo "Number $i" i=$((i + 1)) done
When to Use Which
Choose bash when you want to write scripts with advanced features like arrays, functions, or need a rich interactive shell with command history and tab completion. It is ideal for Linux systems and personal use where bash is available.
Choose sh when you need maximum portability across different Unix and Unix-like systems, especially for simple scripts that must run everywhere without modification. It is best for system scripts and environments where bash may not be installed.
Key Takeaways
bash for powerful scripting and interactive shell features.sh for maximum portability and simple scripts.bash supports advanced syntax like arrays and brace expansion; sh does not.bash-specific features won't run in sh without modification.