Skip to content

Instantly share code, notes, and snippets.

@md5
Last active August 28, 2015 04:42
Show Gist options
  • Save md5/f153ac48286aa790edce to your computer and use it in GitHub Desktop.
Save md5/f153ac48286aa790edce to your computer and use it in GitHub Desktop.
Helper script to ensure that Bash 4 and GNU tools are used on OS X

This helper script can be sourced at the top of another Bash script to ensure that it runs under Bash 4 with GNU grep, readline, sed, and zcat.

It should be sourced in your script like this, before the part of the script that uses Bash 4 features or expects GNU tools:

source .ensure-bash4+gnu-tools.bash "$BASH_SOURCE" "$@"
#!/bin/bash
set -e
SCRIPT="$(basename "$1")"
# Attempt to run under bash 4 if we aren't already
if [ "$BASH_VERSINFO" -lt 4 ]; then
if [ `uname` = Darwin ]; then
if brew info bash &> /dev/null; then
exec "$(brew --prefix bash)/bin/bash" "$@"
else
echo >&2 <<-EOWARN
ERROR: $SCRIPT requires bash 4+. You may use homebrew to install it:
brew install bash
EOWARN
exit 1
fi
else
echo >&2 <<-EOWARN
ERROR: $SCRIPT requires Bash 4+
EOWARN
exit 1
fi
fi
# From https://gist.github.com/bittner/5436f3dc011d43ab7551
# cross-OS compatibility (ggrep, greadlink, gsed, gzcat are GNU implementations for OS X)
if [ `uname` = Darwin ]; then
if which ggrep greadlink gsed gzcat > /dev/null; then
unset GREP_OPTIONS
unalias grep readlink sed zcat &> /dev/null || true
alias grep=ggrep readlink=greadlink sed=gsed zcat=gzcat
shopt -s expand_aliases
else
echo >&2 <<-EOWARN
ERROR: $SCRIPT requires GNU utils for Mac. You may use homebrew to install them:
brew tap homebrew/dupes
brew install coreutils gnu-sed homebrew/dupes/grep
EOWARN
exit 1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment