Ubuntu – How to write a bash completion to complete director names starting at ~/

bashscripts

Imagine I have a bash script called myscript that will only echo it's first argument, which will be a directory name.
Example of usage:
myscript proj1
Where proj1 is a directory for example located at ~/folder1/folder2/proj1 and your current working directory is ~/.
My question is, for this script how could I write a completion rule so that myscript [tab][tab] would list all directories available to echo, starting at ~/. This means that in the first example and assuming those are the only directories at ~/, myscript pro[tab] would complete the expression to myscript proj1.
Can anyone help me to achieve this?

Thanks in advance.

Best Answer

Your description seems odd: If you get just proj1, how do you know what its parent directory is?

Anyway, to give you what you asked for:

# for me, this takes a looooooong time [1]. Do it once and cache it
mapfile -t _all_dir_names < <( find ~ -type d -printf "%f\n" )

# the function you want completion for
myfunc () { echo hello world $*; }

# the completion function
complete_myfunc() {
    local dir cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=()
    for dir in "${_all_dir_names[@]}"; do
        if [[ $dir == "$cur"* ]]; then
            printf -v dir "%q" "$dir"      # protect whitespace in the dir name
            COMPREPLY+=("$dir")
        fi
    done
}

# registering the completion
complete -F complete_myfunc myfunc

[1]: 2 minutes, 66782 directories

Related Question