如何将参数传递给自定义 zsh 函数?
例如:
function kill_port_proc(port) {
lsof -i tcp:<port interpolated here>| grep LISTEN | awk '{print $2}'
}
我在网上看到了很多关于 ZSH 函数的例子,但几乎没有关于传递参数和插入它们的内容。
最佳答案
定义函数时,不能指定必需的参数。这就是为什么同时使用 function
关键字和括号 ()
对我来说似乎没用。
要获取传递的参数,请使用 positional parameters .
The positional parameters provide access to the command-line arguments of a shell function, shell script, or the shell itself; [...]
The parameter
n
, wheren
is a number, is then
th positional parameter. The parameter$0
is a special case [...]
关于
$0
位置参数:The name used to invoke the current shell, or as set by the -c command line option upon invocation.
If the
FUNCTION_ARGZERO
option is set,$0
is set upon entry to a shell function to the name of the function, and upon entry to a sourced script to the name of the script, and reset to its previous value when the function or script returns.
使用您的示例:
function kill_port_proc {
lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'
}
就我个人而言,我喜欢至少通过在定义之前添加函数签名来记录函数。
然后,当我想保护它们免受意外修改时,我为每个参数和只读参数声明局部参数。
如果参数是强制性的,我使用一个特殊的 parameter expansion形式:
${name?word}
${name:?word}
In the first form, if name is set, or in the second form if name is both set and non-null, then substitute its value;
otherwise, print word and exit from the shell. Interactive shells instead return to the prompt.
If word is omitted, then a standard message is printed.
我将如何编写您的示例:
# 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}'
}
关于zsh - 如何将参数传递给自定义 zsh 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127741/