[英]Fish shell script: add a list as a function's argument
I would like to pass a list of variable length as a parameter into a fish function called and defined within a fish script, similar to how $argv
is a list on the top level of a fish script I guess.我想将可变长度列表作为参数传递给在鱼脚本中调用和定义的鱼函数,类似于我猜想
$argv
是鱼脚本顶层列表的方式。
function main_function
function f --argument xs
echo "called f"
echo $xs
end
set xs "one" "two" "three";
f $xs
end
calling function --help
mentions the --inherit-variable
option.调用
function --help
提到了--inherit-variable
选项。 While setting the option causes the xs
variable within the f's scope to be the full list, it makes a dumb copy at the point where the function is defined.虽然设置该选项会使 f 范围内的
xs
变量成为完整列表,但它会在定义函数的位置生成一个哑副本。 I need the variable to be copied when f is called, however.但是,我需要在调用 f 时复制变量。
function main_function
set xs "one" "two" "three";
function f --inherit-variable xs
echo "called f"
echo $xs
end
f $xs
end
As @ridiculous_fish mentioned in the comments, $argv
is defined by and available in any function, regardless of its "level".正如评论中提到的@ridiculous_fish ,
$argv
由任何函数定义并在任何函数中可用,无论其“级别”如何。 So if you need to "copy" a list into the function when it is called (vs. defined ), just pass the item(s) as argument(s) and access using $argv
.因此,如果您需要在调用时将列表“复制”到函数中(与定义相比),只需将项目作为参数传递并使用
$argv
访问。
For instance:例如:
function outer
set --show argv
set xs "one" "two" "three"
function inner
set --show argv
end
inner $xs
end
Calling outer
with no arguments will return:不带参数调用
outer
将返回:
$argv: set in local scope, unexported, with 0 elements
$argv: set in local scope, unexported, with 3 elements
$argv[1]: |one|
$argv[2]: |two|
$argv[3]: |three|
But calling outer four five size
will result in:但是调用
outer four five size
会导致:
$argv: set in local scope, unexported, with 3 elements
$argv[1]: |four|
$argv[2]: |five|
$argv[3]: |six|
$argv: set in local scope, unexported, with 3 elements
$argv[1]: |one|
$argv[2]: |two|
$argv[3]: |three|
Each function's $argv
is distinct, even though they are nested.每个函数的
$argv
都是不同的,即使它们是嵌套的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.