in zsh
, I can autocomplete hostnames from /etc/hosts
, ie:
ssh f<TAB>
will offer completions for hosts starting with f
.
This is configured in /usr/share/zsh/functions/Completion/Unix/_hosts
:
local ipstrip='[:blank:]#[^[:blank:]]#'
zstyle -t ":completion:${curcontext}:hosts" use-ip && useip=yes
[[ -n $useip ]] && ipstrip=
if (( ${+commands[getent]} )); then
_cache_hosts=(${(s: :)${(ps:\t:)${(f)~~"$(_call_program hosts getent hosts 2>/dev/null)"}##${~ipstrip}}})
else
_cache_hosts=(${(s: :)${(ps:\t:)${${(f)~~"$(</etc/hosts)"}%%\#*}##${~ipstrip}}})
fi
....
_hosts=( "$_cache_hosts[@]" )
however, it only works if /etc/hosts
file has the format 'IP' 'hostname', ie:
192.168.1.4 foo.mydomain.com
it will not work if IP is missing:
foo.mydomain.com
How can I modify the completion script, so that hostnames without IP are also completed?
Completion of hostnames without IP from /etc/hosts
works fine in bash_completion
. So I am just trying to get the same behavior on zsh
.
/etc/hosts
and the output ofgetent hosts
actually work like that?~/.hosts
and then setzstyle -e ':completion:*' hosts 'reply=($(< ~/.hosts))'
/etc/hosts
is to associate IP addresses with hostnames. Each line (unless empty or a comment) must have one IP address followed by at least one hostname (the first one should be the canonical hostname, the others are aliases). Lines without IP addresses are not valid.HashKnownHosts
in your ssh configuration (~/.ssh/config
or/etc/ssh/ssh_config
), thanzsh
can also use the entries in~/.ssh/known_hosts
for completion (You may have to remove the the current entries in order to repopulate it with plain text host names).