繁体   English   中英

Fish shell 脚本:添加一个列表作为函数的参数

[英]Fish shell script: add a list as a function's argument

我想将可变长度列表作为参数传递给在鱼脚本中调用和定义的鱼函数,类似于我猜想$argv是鱼脚本顶层列表的方式。

function main_function
   function f --argument xs
      echo "called f"
      echo $xs     
   end
    set xs "one" "two" "three";
    f $xs
end

调用function --help提到了--inherit-variable选项。 虽然设置该选项会使 f 范围内的xs变量成为完整列表,但它会在定义函数的位置生成一个哑副本。 但是,我需要在调用 f 时复制变量。

function main_function
   set xs "one" "two" "three";
   function f --inherit-variable xs
      echo "called f"
      echo $xs     
   end
   f $xs
end

正如评论中提到的@ridiculous_fish , $argv由任何函数定义并在任何函数中可用,无论其“级别”如何。 因此,如果您需要在调用时将列表“复制”到函数中(与定义相比),只需将项目作为参数传递并使用$argv访问。

例如:

function outer
    set --show argv
    set xs "one" "two" "three"
    function inner
        set --show argv
    end
    inner $xs
end

不带参数调用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|

但是调用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|

每个函数的$argv都是不同的,即使它们是嵌套的。

暂无
暂无

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

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