Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Cross-OS compatibility with GNU tools (readlink, sed, zcat, zless, zdiff, ...) for Mac OS X towards Linux
# DESCRIPTION OF PROBLEM: Implementations of sed, readlink, zcat, etc. are different on OS X and Linux.
# NOTE: Put this on top of your script using sed, readlink, zcat, etc. that should work alike on Mac OS X.
# cross-OS compatibility (greadlink, gsed, zcat are GNU implementations for OS X)
[[ `uname` == 'Darwin' ]] && {
which greadlink gsed gzcat > /dev/null && {
unalias readlink sed zcat
alias readlink=greadlink sed=gsed zcat=gzcat
} || {
echo 'ERROR: GNU utils required for Mac. You may use homebrew to install them: brew install coreutils gnu-sed'
exit 1
# NOTE: Now all uses of `sed`, `readlink`, `zcat`, etc. will refer to their GNU implementation in your script below.
# NOTE: In order to use the original implementation for Mac OS X again you'd have to do `unalias ...` (as in line 7 above).
Copy link

bittner commented Jan 16, 2016

As pointed out by bfontaine on StackOverflow you can, alternatively, add /usr/local/opt/coreutils/libexec/gnubin to your PATH (obviously before /usr/bin or so), which will make the commands available without the g prefix -- without the need for this whole script.

Thanks for the hint, @bfontaine!

Copy link

d1vyank commented Nov 15, 2017

Note: If you are using this within a script you will also need to add: 'shopt -s expand_aliases' to the script

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment