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

标签 zsh

如何将参数传递给自定义 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, where n is a number, is the nth 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/

相关文章:

ruby-on-rails - 哦,我的 zsh/Iterm2 自动建议颜色坏了?

bash - 如何使用 stdout 和 stderr io-redirection 从程序中获取理智的错误/警告消息输出?

git - zsh 字符串的长度,可能包含 unicode 和转义字符

terminal - 电力线符号不起作用?

zsh - 计算 zsh 提示的用户可见字符串的长度

linux - 更改登录 shell 时出现问题

zsh - 如何在命令行中获得前一个命令的第 n 个参数?

Vim + zshell,运行 Vim 外部命令后为 "zsh suspended"

linux - 通过管道输出后 $RANDOM 变量似乎没有改变

linux - 如何在 Linux/Unix 上永久设置 $PATH