我已经为我编写或修改的几个不同的脚本提出了这个用例。本质上,我希望选项“-x”的 bash 完成以完成 PATH 上的可执行文件。这是一个包含两个问题的问题。
到目前为止,我遇到了麻烦,因为 bash 不能轻易区分别名、内置函数、函数等和 PATH 上的可执行文件。/usr/share/bash-completion/bash_completion 中的_commands
包装函数完成了上述所有操作,但我没有使用别名、内置函数、函数等,只想完成恰好是可执行文件的命令小路。
例如...如果我输入scriptname -x bas[TAB]
,它应该以 base64、bash、basename、bashbug 完成。
这是我的完成脚本现在的样子:
_have pygsparkle && {
_pygsparkle(){
local cur prev
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
case $prev in
-x|--executable)
# _command
executables=$({ compgen -c; compgen -abkA function; } | sort | uniq -u)
COMPREPLY=( $( compgen -W "$executables" -- "$cur" ) )
return 0
;;
esac
if [[ $cur = -* ]]; then
COMPREPLY=( $( compgen -W '--executable -h --help -x' -- "$cur" ) )
fi
}
complete -F _pygsparkle pygsparkle
}
它似乎按预期工作,但这{ compgen -c; compgen -abkA function; } | sort | uniq -u
是一个非常肮脏的黑客。在 zsh 中,您可以获得 PATH running 上的可执行文件的排序列表print -rl -- ${(ko)commands}
。因此,看来我至少缺少 60 多个 exec,可能是因为uniq -u
正在转储与别名或函数同名的 exec。
有一个更好的方法吗?获取 PATH 上的所有可执行文件的更好命令还是服务于相同目的的预先存在的完成功能?
更新: 好的,所以下面的函数在 1/6 秒内执行,看起来是最好的选择。除非有任何其他建议,否则我可能会结束这个问题。
_executables(){
while read -d $'\0' path; do
echo "${path##*/}"
done < <(echo -n "$PATH" | xargs -d: -n1 -I% -- find -L '%' -maxdepth 1 -mindepth 1 -type f -executable -print0 2>/dev/null) | sort -u
}