Skip to content

Instantly share code, notes, and snippets.

@aarondill
Created November 15, 2024 01:54
Show Gist options
  • Save aarondill/99bf3c29bbc8bc9b01adf84539eb979a to your computer and use it in GitHub Desktop.
Save aarondill/99bf3c29bbc8bc9b01adf84539eb979a to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -euC -o pipefail && shopt -s nullglob globstar
utils=script_utils.sh dir=$(dirname -- "${BASH_SOURCE[0]}") || true
if [ -f "$dir/$utils" ]; then utils="$dir/$utils"; fi
# shellcheck source=./script_utils.sh
. "$utils"
function usage() {
cat <<EOF || true
Usage: $THIS [PATTERN]...
Lists executables present in \$PATH
If PATTERN is specified, it will be passed to grep to filter the executables (OR)
OPTIONS:
-h, --help display this help message
-p, --path <path> use <path> instead of \$PATH
EOF
}
LONGOPTS=help,path: SHORTOPTS=h,p:
ARGSTRING="$(parse_args "$@")" && eval "$ARGSTRING" || exit
path="${PATH:-}"
while true; do
case "$1" in
-h | --help) usage && exit 0 ;;
-p | --path) path="$2" && shift 2 ;;
--) shift && break ;;
*) abort "This is a bug" 3 ;;
esac
done
function get_execs() {
local d f dirs=()
local path="${1:-$PATH}"
path="${path#:}:" # ensure trailing colon
split dirs ":" "$path"
for d in "${dirs[@]}"; do
[ -n "$d" ] || d=.
for f in "$d"/.[!.]* "$d"/..?* "$d"/*; do
if [ -f "$f" ] && [ -x "$f" ]; then
printf '%s\n' "${f##*/}"
fi
done
done
}
function filter() {
# if patterns given, pass them to grep, else output stdin exactly.
[ "$#" -gt 0 ] || { cat || return && return; }
args=()
for pat; do args+=(-e "$pat"); done
grep "${args[@]}"
}
get_execs "$path" | sort -u | filter "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment