Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

bash-completion - completion function defined the first time a command is invoked

I've added a new alias scp_using_rsync, which uses rsync to copy files over SSH with certain options. I wanted to link the bash completion for scp to this alias.

It works when I add this line:

complete -o bashdefault -o default -o nospace -F _scp scp_using_rsync 2>/dev/null || complete -o default -o nospace -F _scp scp_using_rsync

The only problem is that I notice, _scp gets defined in my bash environment, only after I try tab-completion with ssh/scp at least once in that shell. So if I directly run scp_using_rsync in a new shell, I would get the _scp not found error.

The output from typeset -F in a new shell before and after trying tab completion for ssh or scp commands indicate clearly that the following functions get defined after trying tab-completion for the first time:

$ diff ~/.scratch/file1 ~/.scratch/file2
224a225,227
> declare -f _scp
> declare -f _scp_local_files
> declare -f _scp_remote_files
226a230
> declare -f _sftp
230a235,240
> declare -f _ssh
> declare -f _ssh_ciphers
> declare -f _ssh_macs
> declare -f _ssh_options
> declare -f _ssh_suboption
> declare -f _ssh_suboption_check

These functions seem to be defined in /usr/share/bash-completion/completions/ssh in my system.

These are my 2 inter-related questions:

  • How does bash figure out where to pick up the definitions automatically and define them when the completion is tried for the first time ?
  • How should I be linking the bash-completion for scp_using_rsync to scp's bash completion in a similar way ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Bash 4.1 added a new -D option for complete, compgen and compopt:

New complete/compgen/compopt -D option to define a `default' completion: a completion to be invoked on command for which no completion has been defined. If this function returns 124, programmable completion is attempted again, allowing a user to dynamically build a set of completions as completion is attempted by having the default completion function install individual completion functions each time it is invoked.

There's an example from bash's manual:

_completion_loader()
{
     . "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124
}
complete -D -F _completion_loader

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...