Executing a custom path in Bash

I want to write a bash_completion script for my own file system. I have a client program that sends queries to some DB.

Example:

my_prog --ls db_name:/foo/bar/

this command writes to the list of stdout files in the folder db_name:/foo/bar.

I want to enable autocomplete for this. So when I click the tab, a list of options is displayed.

my_prog --ls db_name:/foo/bar/<tab>

but in this case, when I click the tab and there is a single parameter, it replaces the current path entered, so I get the following:

$ my_prog --ls db_name:/foo/bar/<tab>
$ my_prog --ls file

But I want the match to be added to the end of the path entered.

Here is my completion function:

__complete_path()
{
    COMPREPLY=()

    if [[ ${1} == "" ]]
    then
        COMPREPLY=( "/" )
        compopt -o nospace
        return
    fi

    base=${1##*/}
    dir=${1%/*}

    options="my_prog --ls ${db}:${dir}"
    COMPREPLY=( $(compgen -W "${options}" -- ${base} ) )

    compopt -o nospace
}
+4
source share
1 answer

- . stackexchange . , "" , , .

_complete_func()
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    if [ $COMP_CWORD -eq 1 ]; then
    opts="some options for the program"
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
    elif [ $COMP_CWORD -ge 2 ]; then
    local files=("${cur}"*)
        COMPREPLY=( "${files[@]}")
fi
}
complete -o nospace -F complete_func command_to_autocomplete
+1

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


All Articles