Skip to content

Instantly share code, notes, and snippets.

@rawiriblundell
Created May 10, 2018 03:11
Show Gist options
  • Select an option

  • Save rawiriblundell/e2dacdc7c6aa69fb65ff3f913a57f973 to your computer and use it in GitHub Desktop.

Select an option

Save rawiriblundell/e2dacdc7c6aa69fb65ff3f913a57f973 to your computer and use it in GitHub Desktop.
Print a list of all available commands and a short description about them
#!/bin/bash
# Because you never know what crazy systems are out there
if ! command -v apropos >/dev/null 2>&1; then
apropos() { man -k "$*"; }
fi
# A small function to trim whitespace either side of a (sub)string
# shellcheck disable=SC2120
trim() {
if [ -n "$1" ]; then
printf -- '%s\n' "${@}" | awk '{$1=$1;print}'
else
awk '{$1=$1;print}'
fi
}
cmdShortDescr() {
# First, check with 'whatis'
if command -v whatis >/dev/null 2>&1; then
if whatis -r "^$1$" >/dev/null 2>&1; then
whatis -r "^$1$" | cut -d ')' -f2- | trim | head -n 1
return 0
fi
fi
# Next, 'apropos', we assume a regex-less approach just in case
# Otherwise, this follows the same approach as the 'whatis' method
if apropos "$1" >/dev/null 2>&1; then
if apropos "$1" | grep "^$1 " >/dev/null 2>&1; then
apropos "$1" | cut -d ')' -f2- | trim | head -n 1
return 0
fi
fi
# 'help' has an output standard, the second line is what we're after
if help "$1" >/dev/null 2>&1; then
printf -- '- %s' "$(help "$1" | awk 'FNR==2{$1=$1;print}')"
return 0
fi
# We might be dealing with a symlink, in which case
# use 'file' to show where it links to
if [[ -L "$(command -v "$1")" ]]; then
printf -- '- %s' "$(file -b $(command -v "$1"))"
return 0
fi
# Next we try type to catch out keywords, aliases etc
if type "$1" >/dev/null 2>&1; then
printf -- '- %s' "$(type "$1" | head -n 1)"
return 0
fi
# If we make it to this point, no description could be found
printf '###%s###' "Unable to find short description for '$1'"
return 1
}
# Work our way through a sorted output of compgen -c
while read -r; do
printf '%-30s %s\n' "${REPLY}" "$(cmdShortDescr "${REPLY}")"
done < <(compgen -c | sort | uniq)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment