Bash Completing a script to complete a file path after certain argument parameters

I am writing a bash script completion 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

The idea is that after the --*fileand option --out, bash should autofill the file path. Right now I am using " $(ls)", which only completes the file names in the current work path. Any suggestions?

+4
source share
2 answers

You can use compgen -fto fill in file names, for example:

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

However, compgen -fit is not suitable for filling in file names, since it does not fulfill spaces in file names.

_filedir, bash -completion-lib. , (: declare -f _filedir ).

_filedir, :

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

, bash -completion-lib, _filedir() bash comptopt -o compgen -f:

if [[ ${prev} == --*file ]] || [[ ${prev} == --out ]]; then
    comptopt -o filenames 2>/dev/null
    COMPREPLY=( $(compgen -f -- ${cur}) )
elif ...

, ~ , _filedir().

0

Source: https://habr.com/ru/post/1542948/


All Articles