我想以某种方式使用systemctl
命令
systemctl start
(以及stop
和restart
)也为同样的服务触发了systemctl status
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 ...
),但也关注扩展和内存是否会起作用。
我陷入困境(如果命令是systemctl,第一个参数是['stop','start','restart']之一,那么......)
这实际上非常简单,在简单的情况下[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
我想以某种方式使用systemctl命令
这听起来你想要一个“真正的”包装函数,与底层命令同名。这是可能的,只需要在每次调用底层命令时指定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
保留扩展等功能
你不需要在这里做任何事情,因为扩展发生在你的函数被调用之前。
[1]:选项存在一般性问题。如果你做systemctl --user start
,命令是start
,但它不是第一个参数!为了确定命令,你可以跳过以-
开头的所有参数,但是也有选项带参数(例如systemctl --host status start
)。这里的一般解决方案基本上是不可能的,所以你可以做的最好的事情就像fish的argparse,它需要添加工具支持的所有选项,然后重做参数解析。