Bash vs. sh, Zsh, and Fish

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 5 of 205

Bash is one of several command-line shells, and choosing between them depends on what you are doing. For scripts that must run on many machines, the lowest common denominator is the POSIX sh language. For daily interactive work, many people prefer Zsh or Fish for their extra comfort features. Bash sits in between: it is almost universally available, it is a superset of sh for practical purposes, and it has enough scripting features for serious automation.

Understanding the Concept

All the shells in this lesson accept typed commands and run programs, so they look similar at first. They differ in three important ways:

  • Language syntax. Some constructs, such as arrays and [[ ]], exist in one shell and not another.
  • Interactive features. Auto-suggestions, spelling correction, and completion quality vary.
  • Compatibility. Some shells follow the POSIX standard, which allows scripts to move between systems. Others deliberately break from it to offer a cleaner language.

Knowing these differences tells you which shell to use for a given task and why a script that works in one place may fail in another.

The Family Tree

The shells in this lesson are related:

Bourne shell (sh, 1977)
 ├── Bash   (adds arrays, [[ ]], history, completion)
 ├── Zsh    (similar to Bash, with many more features)
 ├── Ksh    (Korn shell; many ideas later adopted by Bash and Zsh)
 └── Dash   (small, fast POSIX shell)

Fish (2005): a separate design, not derived from the Bourne shell

Bash, Zsh, and Dash trace their syntax back to the Bourne shell. Fish was designed from scratch and intentionally uses a different syntax.

Bash vs. sh

sh is the name of the standard system shell. It is not one single program. On different systems, /bin/sh may be a real Bourne shell, a link to Bash running in a compatibility mode, or a link to a smaller shell such as Dash.

You can see what sh is on your system:

ls -l /bin/sh

Output on Debian and Ubuntu:

lrwxrwxrwx 1 root root 4 Mar 31  2024 /bin/sh -> dash

The -> shows that /bin/sh is a symbolic link to dash. On other distributions it may point to Bash.

POSIX and Portability

The POSIX standard describes the commands and syntax that every compliant shell should support. A script that sticks to POSIX features is called a portable script. It runs on any compliant sh, including Dash, Bash in POSIX mode, and BusyBox on small embedded systems.

Bash supports many features outside POSIX. Using them in a script that is run by plain sh leads to errors. The following script uses a Bash array:

names=(Asha Ravi Meena)
echo "${names[1]}"
echo "${#names[@]}"

Running it with Bash:

Ravi
3

Running the same file with Dash gives an error:

t1.sh: 1: Syntax error: "(" unexpected

Dash does not understand array syntax, so it fails on the first line.

Features That Differ

Several commonly used features exist in Bash but not in POSIX sh:

FeatureBashPOSIX sh (Dash)
ArraysYesNo
[[ ... ]] testYesNo
Brace expansion {1..3}YesNo
== inside [ ]AcceptedNot defined; may fail
function name { } keywordYesNo
Process substitution <(...)YesNo

Here are three short comparisons that were tested with Bash 5.2 and Dash.

Brace expansion:

bash -c 'echo {1..3}'
dash -c 'echo {1..3}'

Output:

1 2 3
{1..3}

Bash expands the pattern. Dash prints it literally, because it has no brace expansion.

The double bracket test:

sh -c '[[ a == a ]] && echo yes'

Output when sh is Dash:

sh: 1: [[: not found

Dash treats [[ as the name of a program, cannot find it, and reports the error.

Escape sequences in echo:

bash -c 'echo "a\tb"'
dash -c 'echo "a\tb"'

Output:

a\tb
a	b

Bash prints the backslash and the letter t literally by default, while Dash converts \t into a real tab character. Differences like this are why portable scripts use printf instead of echo when escape sequences matter.

Bash's POSIX Mode

When Bash is started as sh, or with the --posix option, it changes some behaviors to follow the standard more closely:

bash --posix -c 'echo ok'

Output:

ok

POSIX mode narrows a few differences, but it does not make Bash reject every Bash-only feature. Testing with a real POSIX shell such as Dash is the reliable way to check portability.

Bash vs. Zsh

Zsh, the Z shell, is very close to Bash in syntax. Most simple Bash scripts run unchanged in Zsh, and most interactive habits transfer. Zsh has been the default login shell on macOS since macOS Catalina, which is why many Mac users meet it first.

Zsh offers extra interactive features:

  • Stronger tab completion, including menus and completion of options for many commands.
  • More powerful pattern matching in file names.
  • Spelling correction.
  • Themes and frameworks that customize the prompt.

The differences that most often surprise people moving from Bash are in the language:

  • Array indexing starts at 1 in Zsh by default, while Bash starts at 0. A line such as echo ${names[1]} returns the first element in Zsh and the second in Bash.
  • Unquoted variables are not split into words by default in Zsh, while Bash splits them. A script that depends on word splitting may behave differently.
  • Some options are set with setopt in Zsh rather than shopt and set in Bash.

For these reasons, scripts that target Bash should declare Bash in their shebang line even if you use Zsh for typing commands interactively.

Bash vs. Fish

Fish, the friendly interactive shell, takes a different approach. It favors a modern, consistent syntax and an excellent out-of-the-box experience, and it does not try to be compatible with POSIX.

Out of the box, Fish provides:

  • Suggestions as you type, based on your history.
  • Syntax highlighting that shows invalid commands in red before you press Enter.
  • Helpful completions generated from manual pages.

Its language is different from Bash. The same simple task looks like this in each shell.

Bash:

name="Asha"
for city in Chennai Madurai; do
  echo "$name visits $city"
done

Fish:

set name Asha
for city in Chennai Madurai
    echo "$name visits $city"
end

Both print:

Asha visits Chennai
Asha visits Madurai

Notable differences in Fish are that variables are created with set instead of =, blocks end with end instead of done or fi, and the exit status is stored in $status instead of $?. Because a Bash script is not valid Fish, you should keep Bash scripts in files that start with a Bash shebang and run them with Bash even when Fish is your login shell.

Comparing the Shells

Aspectsh (POSIX)BashZshFish
AvailabilityEverywhereAlmost everywhereCommon, default on macOSNeeds installation
POSIX compatibleYesMostlyMostlyNo
ArraysNoYes (index from 0)Yes (index from 1 by default)Yes (lists, index from 1)
Interactive comfortBasicGoodExcellentExcellent
Best forPortable scriptsScripts and daily useDaily interactive useDaily interactive use

Choosing a Shell

A practical rule helps:

  • For scripts shared with others or run on servers you do not control, write for POSIX sh if you can, or declare Bash with #!/usr/bin/env bash if you need Bash features.
  • For automation on Linux systems that you manage, Bash is a safe default because it is nearly always installed.
  • For daily typing, use whichever shell you enjoy. Your login shell and the shell your scripts use do not have to match.

Declaring Which Shell Runs a Script

The first line of a script, called the shebang, names the interpreter. It prevents the wrong shell from running the file:

#!/usr/bin/env bash
echo "Interpreter: $0"
echo "Bash version: ${BASH_VERSION%%(*}"

Running bash show.sh prints:

Interpreter: show.sh
Bash version: 5.2.21

When the first line is #!/bin/sh, the system runs the script with sh instead, and Bash-only features may fail. Choosing the shebang is how a script states its requirements, and a later lesson explains the shebang in detail.

Checking Which Shells Are Installed

The file /etc/shells lists valid login shells, and command -v reports whether a given shell is installed:

command -v zsh fish || echo "zsh and fish not installed"

Output on a system that has neither:

zsh and fish not installed

If a shell is installed, command -v prints its path instead. To try another shell for the current session, type its name, such as zsh, and return to Bash by typing exit.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Bash vs. sh, Zsh, and Fish and get answers drawn from it.

Signed-in readers only.