Skip to content

Instantly share code, notes, and snippets.

@tiagoad
Created July 21, 2026 05:40
Show Gist options
  • Select an option

  • Save tiagoad/f2c30ab385714193fe6342b1b0cda2f5 to your computer and use it in GitHub Desktop.

Select an option

Save tiagoad/f2c30ab385714193fe6342b1b0cda2f5 to your computer and use it in GitHub Desktop.
Find GNU coreutils executable (portable)
#!/bin/sh
is_gnu() {
command -v "$1" >/dev/null \
&& "$1" --help 2>&1 | grep "@gnu.org" >/dev/null
}
get_gnu() {
if is_gnu "$1"; then
# is regular name
echo "$1"
elif is_gnu "g$1"; then
# is g<name> (homebrew coreutils)
echo "g$1"
else
# not found
echo "Error: no gnu coreutils utility found for '$1'" >&2
exit 1
fi
}
# either verify yourself...
grep="$(get_gnu "grep")"
if [ ! "$grep" ]; then exit 1; fi
echo "hello world" | "$grep" -P "^hello"
# ...or set -e (exit immediately if a command exits with a non-zero status)
set -e
grep="$(get_gnu "grep")"
echo "hello world" | "$grep" -P "^hello"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment