繁体   English   中英

如何在fish-shell中定义argv不在命令末尾的函数

[英]How to define a function that the argv is not at the end of the command in fish-shell

如果我想打一个find简称

find dir_name -type d

fd

然后我可以使用fd dir_name来执行命令。

如何定义function或创建alias来完成技巧

如果我什至可以这样做会更好: fd dir-name other_operations等于

在终端中find dir_name -type d other_operations

鱼壳内置文档没有与此有关的信息。

您将这样定义一个函数:

function fd
    find $argv -type d
end

该函数的参数在$argv列表中传递。 在将它们传递给您之前,您可以自由地对其进行切片和切块。

好吧,如果fish适度地遵循了POSIX shell,那么诸如此类功能之一的功能就可以解决问题。

fd() {
    find "$@" -type d
}

要么:

fd() {
    dir="$1"
    shift
    find "$dir" -type d "$@"
}

第一个假设所有参数都是可以在-type d之前的目录或操作数。 第二个假设存在一个目录,然后是其他参数。

除了符号的细节之外,您还可以在fish实现类似的功能。


当然,如果访问http://fishshell.com/ ,尤其是有关如何创建函数的文档,则会发现语法上的相似性有限。

function fd
    find $argv -type d
end

function fd
    find $argv[1] -type d $argv[2..-1]
end

仅当至少有两个参数传递给该函数时,最后一个函数才起作用。 '他很好奇; 在其他地方,不存在的变量将扩展为空,但不会在这样的数组扩展中扩展。 有一个(内置的)命令count ,可用于确定数组中有多少个元素: count $argv将返回数组中的元素数。

因此,该代码的修订版将为:

function fd
    if test (count $argv) -gt 1
        find $argv[1] -type d $argv[2..-1]
    else
        find $argv[1] -type d
    end
end

感谢@Jonathan Leffler,这离不开他的帮助:


至于他的回答, $argv[2..-1] (或$argv[2...-1] )的最后部分是不正确的,似乎fish-shell不支持这种语法,它说:

Could not expand string “$argv[2..-1]

实际上,经过一些测试,事实证明该部分是不必要的,如果$argv是列表,则fish-shell将自动解析$argv的其余部分。


正确的模板是(已经过测试,非常简单):

function fd --description 'List all the (sub)directory names in a direction'
    find $argv[1] -type d
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM