Skip to content

Instantly share code, notes, and snippets.

@knoguchi
Created August 11, 2025 19:39
Show Gist options
  • Save knoguchi/825938801f68cb0ebff3ef81ff0f395f to your computer and use it in GitHub Desktop.
Save knoguchi/825938801f68cb0ebff3ef81ff0f395f to your computer and use it in GitHub Desktop.
Make your Mac GNU first
# __mac_gnu_env.sh
# source this script to make your Mac GNU first
if [[ "$OSTYPE" != darwin* ]]; then
return 1 2>/dev/null || exit 1
fi
pkgs=(bash coreutils findutils gnu-sed grep gawk gnu-tar diffutils make)
# Must be bash
[[ -z "$BASH_VERSION" ]] && {
echo "This script must be sourced from bash, not zsh."
return 1 2>/dev/null || exit 1
}
# Check bash version >= 4
if (( ${BASH_VERSION%%.*} < 4 )); then
echo "Bash 4.0+ is required."
echo "Install and switch to Bash 4+ before sourcing this script."
return 1 2>/dev/null || exit 1
fi
# Must be sourced
(return 0 2>/dev/null) || {
echo "This script must be sourced, not executed."
echo "Usage: source __mac_gnu_env.sh"
exit 1
}
# Cache installed packages once
mapfile -t installed_pkgs < <(brew list --formula)
missing=()
for pkg in "${pkgs[@]}"; do
if ! printf '%s\n' "${installed_pkgs[@]}" | grep -qx "$pkg"; then
missing+=("$pkg")
continue
fi
prefix="$(brew --prefix "$pkg")"
# Prepend libexec/gnubin if exists
if [[ -d "$prefix/libexec/gnubin" ]]; then
[[ ":$PATH:" != *":$prefix/libexec/gnubin:"* ]] && \
PATH="$prefix/libexec/gnubin:$PATH"
fi
# Prepend bin if exists (some packages install binaries here)
if [[ -d "$prefix/bin" ]]; then
[[ ":$PATH:" != *":$prefix/bin:"* ]] && \
PATH="$prefix/bin:$PATH"
fi
done
if (( ${#missing[@]} )); then
echo "Missing packages: ${missing[*]}"
echo "Install with: brew install ${missing[*]}"
return 1 2>/dev/null || exit 1
fi
export PATH
echo "GNU tools ready on Mac. PATH updated."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment