zsh:给定目录中的完整主机名和文件

Mar*_*ter 7 zsh autocomplete

我有一个脚本myscript,它需要两个参数:

  1. 主机名
  2. 目录

我如何编写自己的 zsh 完成,以便每当我这样做


mysript <TAB>
Run Code Online (Sandbox Code Playgroud)

它从我的主机列表中完成(即与sshdo相同)以及何时完成


mysript host1 <TAB>
Run Code Online (Sandbox Code Playgroud)

它从目录中完成/home/martin/test/


Chr*_*her 5

谢谢你的有趣问题。我想在我的脚本中做同样的事情。该文件是密而不那么容易理解; 我还没有学会在脚本中没有实际选项的情况下工作。这是我用实际选项实现目标的第一次尝试。

首先,我创建了一个myscript.sh使用选项命名的 shell 脚本。

#!/usr/bin/env sh
self=$(basename "$0")
hflag=0 # Boolean: hflag is not yet detected
dflag=0 # Boolean: dflag is not yet detected

function usage() {
    echo "Usage: $self [ -h <hostname> | -d <directory> ]"
}

# If no options were given, exit with message and code.
if (($# == 0)); then
    usage
    exit 1
fi

# Process options and option arguments.
while getopts ":h:d:" option; do
    case "${option}" in
        h ) hflag=1 # The h option was used.
            host=${OPTARG} # The argument to the h option.
            ;;
        d ) dflag=1 # The d option was used.
            dir=${OPTARG} # The argument to the d option.
            ;;
        \?) # An invalid option was detected.
            usage
            exit 1
            ;;
        : ) # An option was given without an option argument.
            echo "Invalid option: $OPTARG requires an argument" 1>&2
            exit 1
            ;;
    esac
done

# One of hflag or dflag was missing.
if [ $hflag -eq 0 ] || [ $dflag -eq 0 ]; then
    usage
    exit 1
fi

# Do something with $host and $dir.
# This is where the actions of your current script should be placed.
# Here, I am just printing them.
echo "$host"
echo "$dir"

# Unset variables used in the script.
unset self
unset hflag
unset dflag
Run Code Online (Sandbox Code Playgroud)

接下来,我确定在哪里zsh查找自动完成文件。

print -rl -- $fpath
Run Code Online (Sandbox Code Playgroud)

就我而言,我选择了其中一个目录/usr/local/share/zsh/site-functions。被视为自动完成文件的文件名以下划线_字符开头。我_myscript在目录中创建了文件。后面的部分#compdef是上面的实际脚本名称。

#compdef myscript.sh

_myscript() {
    _arguments '-h[host]:hosts:_hosts' '-d[directory]:directories:_directories'
}

_myscript "$@"
Run Code Online (Sandbox Code Playgroud)

然后我执行compinit以获取_myscript文件提供的新自动完成定义。结果是,我现在可以使用制表符补全来指定选项后的主机和-h选项后的目录,-d同时在解析脚本本身的选项和选项参数时仍保持一定的理智。选项卡完成甚至在调用之前就显示可用选项myscript.sh并使选项顺序无关紧要。

用法变成如下所示。

myscript.sh -h <TAB> -d ~/test/<TAB>
Run Code Online (Sandbox Code Playgroud)

总结解决方案

在第二次尝试中,我创建了一个简单的 shell 脚本zscript.sh.

#!/usr/bin/env sh
echo "$1"
echo "$2"
Run Code Online (Sandbox Code Playgroud)

我创建了一个文件,/usr/local/share/zsh/site-functions/_zscript.

#compdef zscript.sh

_zscript() {
    _arguments '1: :->hostname' '2: :->directory'
    case $state in
    hostname)
        _hosts
    ;;
    directory)
        _directories -W $HOME/test/
    ;;
    esac
}
Run Code Online (Sandbox Code Playgroud)

我执行了compinit