Last active
May 5, 2023 02:12
-
-
Save rcmdnk/8dd36fcf603bec9ae79080c2a24d73e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# mycmd: command wrapper for functions and executables | |
PREFIX="$(basename "$0")-" | |
get_commands () { | |
local array | |
local cmd_cand=() | |
# get functions | |
IFS=' ' read -ra array <<< "$(declare -F |grep "declare -f $PREFIX"|cut -d' ' -f3 | tr $'\n' ' ')" | |
cmd_cand=("${cmd_cand[@]}" "${array[@]}") | |
# get executables | |
local pathes | |
IFS=':' read -ra pathes <<< "$PATH" | |
local p | |
local f | |
local cmd | |
for p in "${pathes[@]}";do | |
if [ ! -d "$p" ];then | |
continue | |
fi | |
while read -r f;do | |
if [ -x "$f" ];then | |
cmd="${f##*/}" | |
cmd_cand+=("$cmd") | |
fi | |
done < <(find "$p" -maxdepth 1 -name "${PREFIX}*") | |
done | |
local commands=() | |
for cmd in "${cmd_cand[@]}";do | |
if [ "$cmd" = "" ];then | |
continue | |
fi | |
c=${cmd/$PREFIX/} | |
commands+=("$c") | |
done | |
echo "${commands[*]}" | |
} | |
mycmd-help () { | |
echo "Usage: mycmd <sub-commands>" | |
echo "Sub commands: $(get_commands)" | |
} | |
mycmd-commands () { | |
get_commands | |
} | |
mycmd-test () { | |
echo "This is mycmd-test" | |
for arg in "$@";do | |
echo "arg: $arg" | |
done | |
} | |
if [ $# -eq 0 ];then | |
mycmd-help | |
exit | |
fi | |
cmd="$1" | |
shift | |
if [[ "$cmd" = "commands" ]];then | |
mycmd-commands | |
exit | |
fi | |
if ! type -t "$PREFIX$cmd" >&/dev/null;then | |
echo "Unknown command: $cmd" | |
mycmd-help | |
exit 1 | |
fi | |
"$PREFIX$cmd" "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment