6

I'd like Bash to stop removing variable names from paths and replacing them by their values. I tried several 'shopts' settings in various bash versions but was not successful in keeping a variable unsubstituted after applying path auto-completion. After entering $APPSERVER and hitting TAB I would like the following result:

$APPSERVER/foo/bar

instead of

/terribly-long-path-to-desired-appserver-instance/foo/bar

The latter one makes extraction of a script afterwards cumbersome. Does anybody know how to set up BASH to auto-complete but leave the variable name in place?

1
  • Have you tried to type the slash before hitting TAB? cd $HOME/<TAB>. BTW recent bash version has shopt -u direxpand Commented Jul 29, 2015 at 12:58

1 Answer 1

1

This gets what you're shooting for mostly working.

example:

$ at_path $HOME D<tab><tab>
Desktop/    Documents/  Downloads/  Dropbox/ 
$ at_path $HOME Doc<tab>
$ at_path $HOME Documents/<tab><tab>
Documents/projects/   Documents/scripts/  Documents/utils/      
Documents/clients/
$ at_path $HOME Documents/cli<tab>
$ at_path $HOME Documents/clients/<enter>
/home/bill-murray/Documents/clients/

copy, and source this file to make it work

#
#  The function to provide the "utility": stitch together two paths
#
at_path () {
  printf "${1}/${2}"
}


#
# The completion function
#
_at_path () {

    # no pollution
    local base_path
    local just_path
    local full_path
    local and_path=${COMP_WORDS[2]}

    # global becasue that's how this works
    COMPREPLY=()

    if [[ ${COMP_WORDS[1]} =~ \$* ]]; then
        base_path=`eval printf "${COMP_WORDS[1]}"`
        full_path=${base_path}/${and_path}
        just_path=${full_path%/*}
        COMPREPLY=( $(find ${just_path} -maxdepth 1 -path "${base_path}/${and_path}*" -printf "%Y %p\n" |\
                      sed -e "s!${base_path}/!!" -e '/d /{s#$#/#}' -e 's/^. //' 2> /dev/null) )
    else
        COMPREPLY=()
    fi

}

#
# and tell bash to complete it
#
complete -o nospace -F _at_path at_path

This answer turned into quite the rabbit-hole, i'll be keeping my eye out for anyone else's solution! Good luck!

You must log in to answer this question.