Bash:使用自动完成时如何避免变量名替换?

Bash:使用自动完成时如何避免变量名替换?

我希望 Bash 停止从路径中删除变量名并用它们的值替换它们。我在各种 bash 版本中尝试了几种“shopts”设置,但在应用路径自动完成后未能成功保持变量未被替换。输入 $APPSERVER 并点击 TAB 后,我想要以下结果:

$APPSERVER/foo/bar

代替

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

后一种使得事后提取脚本变得很麻烦。有人知道如何将 BASH 设置为自动完成但保留变量名称吗?

答案1

这就是你想要的大多在职的。

例子:

$ 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/

复制并获取该文件以使其正常工作

#
#  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

这个答案变得相当兔子洞,我会密切关注其他人的解决方案!祝你好运!

相关内容