bashfunctionbash-completionpathname

Bash completion in function?


I currently have the following Bash function:

function xcd {
        if [ "$#" -gt 1 ]; then
                echo "Usage: xcd [<path>]" >&2
                return 1
        fi

        cd "/some/commonly/used/path/${1}"
}

I'd like for this to support Bash completion - when I type xcd foo, I'd like it to complete as though I'd typed cd /some/commonly/used/path/foo. Is there any way to get Bash to be smart about this - presumably by observing how ${1} is used - without just writing a Bash completion by hand?


Solution

  • Replace your function in your ~/.bashrc with this:

    CDPATH="/some/commonly/used/path"
    

    I assume that CDPATH is not used so far. Source your ~/.bashrc and then you can use cd foo with bash's completion.