Bash完成使'cd'命令从其他正在运行的shell中完成工作目录?

Tho*_*mas 5 bash cd completion

我正在尝试编写一个bash完成,它将让我完成其他shell所在的目录名称.

例如,假设我有另一个外壳打开/very/long/path/name,目前在包含子目录的目录,我foobar.当我输入时cd <Tab>,我想看到:

$ cd <Tab>
foo/  bar/  /very/long/path/name
Run Code Online (Sandbox Code Playgroud)

我有这个命令来生成潜在的完成列表:

ps -Cbash -opid= | xargs pwdx | cut -d" " -f2 | sort -u | while read; do echo ${REPLY#$PWD/}; done | grep -v "^$"
Run Code Online (Sandbox Code Playgroud)

为简洁起见,我将其写为...pipeline....

在我的系统上有一个_cd产生常规完成的函数:

$ complete -p cd
complete -o nospace -F _cd cd
Run Code Online (Sandbox Code Playgroud)

我想重用这个_cd函数,因为它是非常重要的(约30行代码,根据type _cd).如果解决方案重用已经定义的任何完成,则奖励点,无论它是否基于被调用的函数_cd.

我认为-C选择complete听起来很有希望,但我无法让它发挥作用:

$ complete -C '...pipeline...' cd
$ cd <Tab>grep: cd: No such file or directory
grep: : No such file or directory
grep: cd: No such file or directory
Run Code Online (Sandbox Code Playgroud)

编写我自己的包装函数-F,它附加到COMPREPLY数组,也不是很有效:

$ function _cd2() { _cd; COMPREPLY=( ${COMPREPLY[@]} $(...pipeline...) ); }
$ cd <Tab>
foo/  bar/  name/
Run Code Online (Sandbox Code Playgroud)

它剥离除了最后一个之外的所有路径组件.我认为它必须是由此设置的东西_cd,但我不确定如何抵消它.

如果我_cd从中删除了呼叫_cd2,我确实看到了完成,但它们没有正确完成部分目录名称.如果我键入cd /ve<Tab>,它仍然显示完整路径,而不实际完成我的命令行.

我怎样才能做到我想要的呢?


附录:完整定义_cd:

$ type _cd
_cd is a function
_cd () 
{ 
    local cur prev words cword;
    _init_completion || return;
    local IFS='
' i j k;
    compopt -o filenames;
    if [[ -z "${CDPATH:-}" || "$cur" == ?(.)?(.)/* ]]; then
        _filedir -d;
        return 0;
    fi;
    local -r mark_dirs=$(_rl_enabled mark-directories && echo y);
    local -r mark_symdirs=$(_rl_enabled mark-symlinked-directories && echo y);
    for i in ${CDPATH//:/'
'};
    do
        k="${#COMPREPLY[@]}";
        for j in $( compgen -d $i/$cur );
        do
            if [[ ( -n $mark_symdirs && -h $j || -n $mark_dirs && ! -h $j ) && ! -d ${j#$i/} ]]; then
                j+="/";
            fi;
            COMPREPLY[k++]=${j#$i/};
        done;
    done;
    _filedir -d;
    if [[ ${#COMPREPLY[@]} -eq 1 ]]; then
        i=${COMPREPLY[0]};
        if [[ "$i" == "$cur" && $i != "*/" ]]; then
            COMPREPLY[0]="${i}/";
        fi;
    fi;
    return 0
}
Run Code Online (Sandbox Code Playgroud)

bis*_*hop 1

您需要根据组合选项列表评估当前匹配。这是一个说明移动部件的测试脚本:

#!/bin/bash

mkdir -p {my,other}/path/to/{a,b,c}

function _cd() {
    COMPREPLY=( my/path/to/a my/path/to/b );
}
complete -o nospace -F _cd cd

function _cd2() {
    local cur opts;
    cur="${COMP_WORDS[COMP_CWORD]}";
    _cd;
    opts="${COMPREPLY[@]} other/path/to/c";        # here we combine options
    COMPREPLY=($(compgen -W "${opts}" -- ${cur})); # here is the secret sauce
}
complete -F _cd2 cd

complete -p cd
Run Code Online (Sandbox Code Playgroud)

最重要的一点是:从组合选项集中选择最合适的选项(在compgen)中。_cd2$opts