Bash完成脚本可在某些参数选项后完成文件路径 [英] Bash Completion script to complete file path after certain arguments options

查看:72
本文介绍了Bash完成脚本可在某些参数选项后完成文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为命令行工具编写bash完成脚本:

I am writing a bash completion script for a command-line tool:

_plink()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="--1 --23file --a1-allele --a2-allele --adjust --aec"

    if [[ ${cur} == --*file ]] || [[ ${cur} == --out ]]; then
        COMPREPLY=( $(compgen -W "$(ls)" -- ${cur}) )
    elif [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}
complete -F _plink plink1.9

这个想法是,如果在选项--*file--out之后,bash应该自动完成文件路径. 现在,我使用的是"$(ls)",它仅完成当前工作路径中的文件名.有什么建议吗?

The idea is if the after the option --*file and --out, bash should autocomplete the file path. Right now I am using "$(ls)" which only completes the filenames in current working path. Any suggestions?

推荐答案

您可以使用compgen -f来完成文件名,例如:

You can use compgen -f to complete filenames, like this:

if [[ ${prev} == --*file ]] || [[ ${prev} == --out ]]; then
    COMPREPLY=( $(compgen -f -- ${cur}) )
elif ...

但是,compgen -f不能很好地完成文件名,因为它不支持文件名中的空格.

However, compgen -f isn't great at completing filenames because it doesn't honour spaces in filenames.

一种更好的方法是使用 bash-completion-lib .它可能已经在您的系统上可用(键入:declare -f _filedir进行检查).

A better way is to use the _filedir function available in bash-completion-lib. It might already be available on your system (type: declare -f _filedir to check).

使用_filedir,您的完成功能将变为:

Using _filedir, your completion function becomes:

if [[ ${prev} == --*file ]] || [[ ${prev} == --out ]]; then
    _filedir
elif ...

这篇关于Bash完成脚本可在某些参数选项后完成文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆