ambakshi
5/24/2013 - 9:26 PM

Create bash functions to call GNU coreutils version of UNIX tools on OSX.

Create bash functions to call GNU coreutils version of UNIX tools on OSX.

# On OSX, some utilities (tar, sed, etc) are totally outdated. You can
# brew install coreutils to get around this, but the tools are named gsed,
# gtar, etc.
setup_coreutils () {
    if [ "`uname -o`" == "Darwin" ]; then
        PATH="/usr/local/bin:$PATH" && hash -r
        if [ ! -e /usr/local/bin/gln ]; then
            printf "On OSX you need GNU coreutils. Please install brew and coreutils.\n\n"
            printf " ruby -e \"\$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)\" && sudo brew install coreutils\n\n\n" >&2
            exit 2
        fi
    fi

    local prog= binary=
    for prog in printf echo date dirname basename readlink \
                rm ln tar awk sed sort uniq tail head paste \
                cut chown chmod mkdir rmdir seq cat md5sum \
                wc kill join split tr; do
        binary="`which g${prog} 2>/dev/null`" || binary="`which $prog 2>/dev/null`"
        if [ $? -ne 0 ] || [ -z "$prog" ]; then
            echo "Failed to find g$prog or $prog in \$PATH" >&2
            exit 2
        fi
        # Dynamically create function that call the GNU version
        eval "$prog () { $binary \"\$@\"; } && export -f $prog"
    done
}
setup_coreutils