如何将参数传递给自定义 zsh 函数?

GN.*_*GN. 14 zsh

如何将参数传递给自定义 zsh 函数?
例如:

function kill_port_proc(port) {
    lsof -i tcp:<port interpolated here>| grep LISTEN | awk '{print $2}'
}
Run Code Online (Sandbox Code Playgroud)

我在网上看到了很多关于 ZSH 函数的例子,但几乎没有关于传递参数和插入它们的内容。

Dam*_*ent 29

定义函数时,不能指定必需的参数。这就是为什么同时使用function关键字和括号()对我来说似乎没用的原因。

要获取传递的参数,请使用位置参数

位置参数提供对 shell 函数、shell 脚本或 shell 本身的命令行参数的访问;[...]

参数n,其中n是一个数字,是第nth 个位置参数。该参数$0是一个特例 [...]

关于$0位置参数:

用于调用当前 shell 的名称,或在调用时由 -c 命令行选项设置的名称。

如果FUNCTION_ARGZERO设置了该选项,$0则在进入 shell 函数时将其设置为函数名称,在进入源脚本时将其设置为脚本名称,并在函数或脚本返回时重置为其先前的值。

使用您的示例:

function kill_port_proc {
    lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我喜欢至少通过在定义之前添加函数签名来记录函数。

然后,当我想保护它们免受意外修改时,我为每个参数和只读参数声明局部参数。

如果参数是强制性的,我使用特殊的参数扩展形式:

${name?word}

${name:?word}

在第一种形式中,如果 name 已设置,或者在第二种形式中,如果 name 既设置又非 null,则替换其值;

否则,打印 word 并退出 shell。交互式 shell 反而返回到提示。

如果省略 word,则打印标准消息。

我将如何编写您的示例:

# kill_port_proc <port>
function kill_port_proc {
    readonly port=${1:?"The port must be specified."}

    lsof -i tcp:"$port" | grep LISTEN | awk '{print $2}'
}
Run Code Online (Sandbox Code Playgroud)

  • 如果在每次获取 bash_profile 时声明函数时省略“()”,则函数将被执行。 (4认同)
  • @219CID 我的答案是针对 Zsh 的。使用符合 POSIX 标准的语法可在 shell 之间移植。 (2认同)

Tat*_*aki 11

my_function() {
  if [ $# -lt 2 ]
  then
    echo "Usage: $funcstack[1] <first-argument> <second-argument>"
    return
  fi

  echo "First argument: $1"
  echo "Second argument: $2"
}
Run Code Online (Sandbox Code Playgroud)

用法

$ my_function
Usage: my_function <first-argument> <second-argument>

$ my_function foo
Usage: my_function <first-argument> <second-argument>

$ my_function foo bar
First argument: foo
Second argument: bar
Run Code Online (Sandbox Code Playgroud)