如何仅针对某些参数丰富命令?

How to enrich a command for some parameters only?

我想以

的方式使用 systemctl 命令

我目前有一个

形式的原始解决方案
function sys --wraps systemctl -d "Start service and show its status"
    systemctl restart $argv
    systemctl status $argv
end

但不仅我经常忘记使用它,而且它非常有限。

我相信首先要对第一个参数做出有条件的决定,然后链 systemctl <parameter 1> <parameter 2> 或只是 运行 systemctl <parameter 1> ...

我卡在了条件 (if the command is systemctl and first argument is one of ['stop', 'start', 'restart'] then ...),但也卡在了扩展和内存是否有效的问题上。

I am stuck at the condition (if the command is systemctl and first argument is one of ['stop', 'start', 'restart'] then ...)

这实际上很简单,在简单的情况 [1] 中,特别是因为您 不需要 需要检查 systemctl - 您想要 运行 sys start,不是sys systemctl start,你呢?

所以条件变为:

if contains -- $argv[1] start stop restart
     systemctl $argv
     systemctl status $argv[2..-1]
else
     systemctl $argv
end

可以简化为

systemctl $argv
if contains -- $argv[1] start stop restart
    systemctl status $argv[2..-1]
end

I would like to use the systemctl command in a way where

这听起来您想要一个 "true" 包装函数,其名称与底层命令相同。这是可能的,只是它需要在每次调用底层命令时指定command $thething

还要记住,即使 shell 不是交互式的,fish 函数通常也是可用的,所以如果您有任何脚本调用包装的东西,它们最终会调用该函数。

所以你做类似的事情

# --wraps isn't necessary because the name is the same.
function systemctl
    # without `command`, this will be an infinite loop
    command systemctl $argv
    if contains -- $argv[1] start stop restart
        command systemctl status $argv[2..-1]
    end
end

features such as expansion are retained

您无需在此处执行任何操作,因为展开发生在之前您的函数被调用。


[1]: 选项存在普遍问题。如果你做systemctl --user start,命令是start,但它不是第一个参数!为了确定命令,您可以跳过所有以 - 开头的参数,但也有带参数的选项(例如 systemctl --host status start)。这里的一般解决方案基本上是不可能的,所以你能做的最好的就是像 fish 的 argparse,它需要添加该工具支持的所有选项,然后重新进行参数解析。