是否可以使用 sftp 完成选项卡?

Oli*_*nde 17 command-line sftp auto-completion

有时我需要快速将文件从远程服务器复制到本地计算机。这是我目前的工作流程:

  1. 我通过 SSH 连接到我的远程服务器,找到该文件并复制其完整路径。
  2. 我打开新的终端选项卡并输入:

sftp user@hostname:/path/to/file (其中 /path/to/file 是我之前复制的路径)

这不是很痛苦,但如果我可以跳过第 1 步并在键入 sftp 命令时直接使用制表符完成找到文件的路径,那就太好了。

为了说明这一点,我可以开始输入sftp user@hostname:/pressTAB并获取 / 中的文件夹列表。然后我可以继续输入hopress TAB,它会自动完成home,等等。

我不确定这样的功能是否存在,否则理论上是否可以按照描述编写自定义选项卡完成脚本?关于从哪里开始的任何指示?

Oli*_*nde 8

感谢 shellholic 的回答,我能够让它(在某种程度上)适用于 sftp。首先,创建/etc/bash_completion.d/sftp包含以下内容的文件:

# custom sftp(1) based on scp
# see http://askubuntu.com/questions/14645/is-it-possible-to-get-tab-completion-with-sftp
#
_sftp()
{
    local configfile cur userhost path prefix

    COMPREPLY=()
    cur=`_get_cword ":"`

    _expand || return 0

    if [[ "$cur" == *:* ]]; then
        local IFS=$'\t\n'
        # remove backslash escape from :
        cur=${cur/\\:/:}
        userhost=${cur%%?(\\):*}
        path=${cur#*:}
        # unescape spaces
        path=${path//\\\\\\\\ / }
        if [ -z "$path" ]; then
            # default to home dir of specified user on remote host
            path=$(ssh -o 'Batchmode yes' $userhost pwd 2>/dev/null)
        fi
        # escape spaces; remove executables, aliases, pipes and sockets;
        # add space at end of file names
        COMPREPLY=( $( ssh -o 'Batchmode yes' $userhost \
            command ls -aF1d "$path*" 2>/dev/null | \
            sed -e "s/[][(){}<>\",:;^&\!$=?\`|\\ ']/\\\\\\\\\\\\&/g" \
            -e 's/[*@|=]$//g' -e 's/[^\/]$/& /g' ) )
        return 0
    fi

    if [[ "$cur" = -F* ]]; then
        cur=${cur#-F}
        prefix=-F
    else
        # Search COMP_WORDS for '-F configfile' or '-Fconfigfile' argument
        set -- "${COMP_WORDS[@]}"
        while [ $# -gt 0 ]; do
            if [ "${1:0:2}" = -F ]; then
                if [ ${#1} -gt 2 ]; then
                    configfile="$(dequote "${1:2}")"
                else
                    shift
                    [ "$1" ] && configfile="$(dequote "$1")"
                fi
                break
            fi
            shift
        done

        [[ "$cur" == */* ]] || _known_hosts_real -c -a -F "$configfile" "$cur"
    fi
    # This approach is used instead of _filedir to get a space appended
    # after local file/dir completions, and $nospace retained for others.
    local IFS=$'\t\n'
    COMPREPLY=( "${COMPREPLY[@]}" $( command ls -aF1d $cur* 2>/dev/null | sed \
        -e "s/[][(){}<>\",:;^&\!$=?\`|\\ ']/\\\\&/g" \
        -e 's/[*@|=]$//g' -e 's/[^\/]$/& /g' -e "s/^/$prefix/") )

    return 0
}
complete -o nospace -F _sftp sftp
Run Code Online (Sandbox Code Playgroud)

然后在 bash 中,您需要执行. /etc/bash_completion.d/sftp以加载脚本。

我真正做的只是复制/粘贴 scp 完成脚本,/etc/bash_completion.d/ssh并用 sftp 替换 scp 出现。


poo*_*lie 5

另一种选择:lftp改用它,它具有出色的内置选项卡完成功能(但是一旦您启动它,而不是在 shell 中就可以了。)它可以讨论 sftp 和许多其他协议。