自动检测 shell 脚本中可能的参数以完成

use*_*423 3 unix bash shell zsh

这是一个 shell 脚本,它根据调用的参数执行一些操作:

if [ $1 = "-add" ] 
then
    ...
elif [ $1 = "-remove" ]
    ...
else
    ...
fi
Run Code Online (Sandbox Code Playgroud)

脚本是可执行的(在/usr/bin目录中创建了指向它的链接)。因此,我可以通过指定 .txt 文件中添加的链接名称从 shell 调用它/usr/bin

我想要的是在调用过程中自动检测脚本可能的参数(在我的例子中是-add, )。-remove这意味着当我键入与脚本调用相关的命令,然后键入-re并按选项卡按钮时,它会提示它-remove并为我自动填充它。

需要如何定义参数才能达到这一目标?

尝试在 shell 配置文件中创建别名或在/usr/bin目录中为所有可能的输入创建几个链接,并且工作正常,但我认为这不是最佳解决方案。

Beg*_*man 6

虽然它确实需要在脚本之外进行一些配置,但添加自动完成选项相当容易。

下面是一个 ~/.bash_completion 文件的简单示例,它将自动完成--add--remove添加到命令yourscript。在现实世界中,您可能希望通过直接查询脚本来生成选项;为了简单起见,它们在这里被硬编码。

_yourscript_complete()
{
    # list of options for your script
    local options="--add --remove"

    # current word being completed (provided by stock bash completion)
    local current_word="${COMP_WORDS[COMP_CWORD]}"

    # create list of possible matches and store to ${COMREPLY[@}}
    COMPREPLY=($(compgen -W "${options}" -- "$current_word"))
}
complete -F _yourscript_complete yourscript
Run Code Online (Sandbox Code Playgroud)

请注意, ~/.bash_completion 仅在登录期间获取,因此您需要生成另一个登录 shell 才能查看操作中的更改。您可能还需要在系统上启用用户 bash_completion 文件的来源。

结果:

$ yourscript --<tab><tab>
--add     --remove
Run Code Online (Sandbox Code Playgroud)