Bash 4 has some nice new features, and here’s how to update to Bash 4 on Mac.
Bash version can be queried with the
$ bash --version 3.2.53(1)-release
The actual installation is going to happen with HomeBrew, the Mac package manager, if you don’t have it, you can check the installation instructions from brew.sh:
$ mkdir homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew
Update the homebrew packet database and install bash 4:
$ brew update && brew install bash
bash --version might show
4.x version, but bash might still be using the
3.x version. It’s pretty straightforward to test, the global variable
$BASH_VERSION returns bash version in use.
You can try to make a test file and echo it out there:
#!/bin/bash # version-test.sh echo $BASH_VERSION
Make it executable and run it:
$ chmod +x version-test.sh $ ./version-test.sh 3.2.53(1)-release
You might get the old bash version there. The trick is the shebang on the first line, it’s pointing to the old bash. Change it to:
#!/usr/local/bin/bash # version-test.sh echo $BASH_VERSION
Now, make sure it’s executable and run the test file
$ ./version-test.sh, it should show Bash 4.
Noteworthy thing: that Bash 4 shebang:
#!/usr/local/bin/bash, won’t work on most Linux systems, so your script is not very portable. What you want to use is,
#!/usr/bin/env bash, by using
env it tries to look for Bash from your path.
If you run:
$ which bash
It will show you most likely,
/bin/bash. You might want to add the new bash to your path by editing the
./.bash_profile files, by adding the following line:
# .bash_profile export PATH="/usr/local/bin:$PATH"
$ which bashshould give you the Homebrew installation,
#!/usr/bin/env bashshould use the Bash 4 installation.
Add the new shell to the list of allowed shells:
$ sudo bash -c 'echo /usr/local/bin/bash >> /etc/shells'
Change to the new shell:
$ chsh -s /usr/local/bin/bash
Now close/refresh you terminal session.
Bash version 4 supports associative arrays, plus bunch of other stuff.
#!/bin/bash still points to the system version of Bash, and that’ okay.
sh command that you use to run bash scripts in Mac OS X also still points to the system Bash version. It important to keep it like that, since the system uses it to do updates and what not. You might not want to mess with that.
If you wonder what shells you have at your disposal, you cat out the shell file:
Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @intterne if you want to make a correction etc.