Bash on macOS
Update 2023-12-03: This post was originally written in 2020. The homebrew path has since changed as well as Apple’s move to Arm. The post has been updated to reflect these changes.
Like many Mac users, ever since Catalina, I’d been getting the following prompt every time I open a shell:
The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
I had been putting off the change, but recently got around to making this change. Is said that Apple is changing the default shell to zsh due to licensing issues. It also appears that a lot of people like zsh. I’ve been using bash for a very long time and have found it reliable and sufficient for my needs. Therefore, I installed a different version of Bash and made that my default shell.
The built-in version of Bash is installed at /bin/bash
:
$ /bin/bash --version
GNU bash, version 3.2.57(1)-release (arm64-apple-darwin23)
Copyright (C) 2007 Free Software Foundation, Inc.
Here are the steps to install the latest version using Homebrew:
# Update brew.
brew update
# Install Bash.
brew install bash
# Whitelist new bash.
sudo sh -c 'echo "/opt/homebrew/bin/bash" >> /etc/shells'
# Set it as default for current user.
chsh -s /opt/homebrew/bin/bash
# Install bash-completion.
brew install bash-completion
There are a couple of .bash_profile
customizations I’ve found useful. One is writing history to daily files. Another is updating the prompt so that current user and path are colorized and the command line is on a new line. Below is the relevant lines from my .bash_profile
:
# Get aliases and functions.
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# Set colors/font-weights.
CUSER="\[$(tput setaf 2)\]" # green
CPATH="\[$(tput setaf 4)\]" # blue
BOLD="\[$(tput bold)\]"
RESET="\[$(tput sgr0)\]"
CCOLOR=$YELLOW
# Custom prompt.
export PS1="\n${CUSER}\u@\h${RESET}:${CPATH}${BOLD}\w${RESET}\n$ "
# Must create ~/.logs directory first.
# Write each command to a log file.
export PROMPT_COMMAND='if [ "$(id -u)" -ne 0 ]; then echo "$(date "+%Y-%m-%d.%H:%M:%S") $(pwd) $(history 1)" >> ~/.logs/bash-history-$(hostname)-$(date "+%Y-%m-%d").log; fi'
# Write last command to history on each prompt.
export PROMPT_COMMAND="history -a; $PROMPT_COMMAND"
# Don't put duplicate lines in the history.
export HISTCONTROL=ignoredups:ignorespace
# Append to the history file, don't overwrite it.
shopt -s histappend
# Check window size after each command and update LINES and COLUMNS.
shopt -s checkwinsize
# Set editor for things like crontab
export EDITOR=vim
Here are some other cool colors/font weights for the prompt:
RED="\[$(tput setaf 1)\]"
GREEN="\[$(tput setaf 2)\]"
YELLOW="\[$(tput setaf 3)\]"
BLUE="\[$(tput setaf 4)\]"
MAGENTA="\[$(tput setaf 5)\]"
CYAN="\[$(tput setaf 6)\]"
WHITE="\[$(tput setaf 7)\]"
GRAY="\[$(tput setaf 8)\]"
BOLD="\[$(tput bold)\]"