![](/img/trans.png)
[英]How define a fish shell function that searches for a pattern within certain files?
[英]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
至于他的回答, $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.