Using Bash on macOS

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

macOS is built on a Unix foundation, so Bash is available in every Mac. However, Apple ships a very old Bash version and has used Zsh as the default login shell since macOS Catalina (10.15). This lesson explains what you get out of the box, how to open Bash, how to install a modern version with Homebrew, and how to make your scripts pick the right one.

Understanding the Concept

Three facts explain most of the surprises people meet on a Mac:

  1. The built-in Bash is version 3.2. Apple has kept it at 3.2 for many years because later versions are released under the GNU General Public License version 3, while 3.2 uses version 2. The built-in copy is located at /bin/bash.
  2. The default interactive shell is Zsh. New user accounts open Zsh in the Terminal app. Bash still exists, but you must ask for it.
  3. A newer Bash can be installed alongside the old one. Package managers such as Homebrew install the current release in a separate location, leaving the system copy untouched.

The old version matters because many features in this tutorial, such as associative arrays and some newer expansions, need Bash 4 or later. Bash 3.2 does not have them.

Opening Terminal and Checking Your Shell

Open the Terminal app (found in Applications, then Utilities, or through Spotlight search). To find out which shell your session runs, use:

echo "$SHELL"

On a recent Mac the output is normally:

/bin/zsh

SHELL shows your configured login shell. To see which shell is actually running in this window:

ps -p $$ -o comm=

This prints the name of the current shell process, for example zsh.

Using the Built-In Bash

To start the system Bash from the Terminal, type:

bash

A new Bash session starts inside your current window. Check its version:

echo "$BASH_VERSION"

On a stock Mac the output looks like:

3.2.57(1)-release

The exact patch number may differ, but the major and minor numbers will be 3.2. Type exit to return to Zsh.

Running a script with the system Bash is the same as on any other system:

bash myscript.sh

The script runs under Bash 3.2, so it must avoid features introduced later.

Installing a Modern Bash with Homebrew

Homebrew is a widely used package manager for macOS. After installing Homebrew by following the instructions on its official website, install Bash with:

brew install bash

Homebrew places the new program under its own directory instead of replacing /bin/bash:

  • On Apple Silicon Macs, the Homebrew prefix is /opt/homebrew, so the new Bash is at /opt/homebrew/bin/bash.
  • On Intel Macs, the prefix is /usr/local, so it is at /usr/local/bin/bash.

Confirm which Bash each path runs:

/bin/bash --version | head -1
/opt/homebrew/bin/bash --version | head -1

The first line reports version 3.2.x and the second reports a current 5.x release. Use the path that matches your Mac's processor.

Check which one your plain bash command finds:

type -a bash

The output lists every bash found on your PATH, in order. The first entry is the one that runs when you type bash. If Homebrew's directory comes before /bin in your PATH, you get the new version.

Making Scripts Use the Right Bash

A script chooses its interpreter with the shebang line. The portable form is:

#!/usr/bin/env bash

The env program searches PATH for bash, so the script uses whichever Bash comes first. On a Mac with Homebrew in PATH, that is the modern version. In contrast, #!/bin/bash always selects Apple's old Bash 3.2.

A script can also protect itself by checking the version at the start:

#!/usr/bin/env bash
if (( BASH_VERSINFO[0] < 4 )); then
  echo "This script needs Bash 4 or newer. Found: $BASH_VERSION" >&2
  exit 1
fi
echo "Bash $BASH_VERSION is new enough"

Run on Bash 5.2, it prints:

Bash 5.2.21(1)-release is new enough

Run on Bash 3.2, it prints the error message to standard error and exits with status 1. The (( ... )) form evaluates an arithmetic comparison, and >&2 sends the message to the error stream so it is not mixed with normal output.

Making Bash Your Login Shell

If you prefer Bash for interactive use, you can change the login shell. First add the Bash you want to the list of allowed shells. For a Homebrew Bash on Apple Silicon:

echo /opt/homebrew/bin/bash | sudo tee -a /etc/shells

The command appends the path to /etc/shells. The tee -a form is used because a plain >> redirection would run without administrator rights. Then switch:

chsh -s /opt/homebrew/bin/bash

Open a new Terminal window for the change to take effect. For the system Bash, use chsh -s /bin/bash instead, which is already allowed. You may also see a notice from Apple that the default shell is now Zsh and that the Bash you are using is old. That message is informational.

Start-Up Files on macOS

The Terminal app starts each new window as a login shell, which affects which configuration files Bash reads. A login Bash reads ~/.bash_profile first, and only falls back to ~/.bash_login and then ~/.profile when it is missing. It does not read ~/.bashrc automatically. A common arrangement is to load ~/.bashrc from ~/.bash_profile:

# ~/.bash_profile
if [ -f "$HOME/.bashrc" ]; then
  source "$HOME/.bashrc"
fi

The condition checks that the file exists, and source runs its commands in the current shell. A later lesson covers all the start-up files in detail.

Differences from Linux Commands

Many everyday commands on macOS come from BSD, whereas Linux uses GNU versions. The same name can accept different options. For instance, sed -i on GNU systems edits files in place with no extra argument, while the BSD version on macOS needs a backup suffix argument, such as sed -i ''. Likewise, options of date, stat, and ls differ.

You can install the GNU versions with Homebrew, for example brew install coreutils, and they appear with a g prefix such as gdate. When writing scripts that must run on both Linux and macOS, test them on both, or restrict yourself to options that both versions share.

macOS Defaults at a Glance

ItemmacOS default
Default login shellZsh (since Catalina)
Built-in BashVersion 3.2 at /bin/bash
Modern Bash sourceHomebrew
Homebrew Bash path/opt/homebrew/bin/bash (Apple Silicon) or /usr/local/bin/bash (Intel)
Login-shell start-up file~/.bash_profile
Core utilitiesBSD versions

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 Using Bash on macOS and get answers drawn from it.

Signed-in readers only.