Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass arguments to custom zsh functions?

Tags:

zsh

How do you pass arguments to custom zsh functions?
For instance:

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

I'm seeing so many examples online with ZSH functions, but there barely anything on passing arguments and interpolating them.

like image 339
GN. Avatar asked Mar 12 '19 17:03

GN.


People also ask

Do Bash functions work in zsh?

The ZSH shell is an extended version of the Bourne Again Shell; thus, most commands and scripts written for bash will work on ZSH.

What is Precmd zsh?

precmd is executed before your prompt is displayed and is often used to set values in your $PROMPT . preexec is executed between when you press enter on a command prompt but before the command is executed. Each hook is an array of widgets which are executed by zsh.

What is zsh autoload?

The autoload command essentially instructs Zsh to register a function (called clock) using the contents of the clock file that is located in a directory somewhere along the fpath.


1 Answers

When defining a function, you cannot specify required arguments. That's why using both the function keyword and parens () seems useless to me.

To get the passed arguments, use 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 [...]

About the $0 positional parameter:

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.

Using your example:

function kill_port_proc {
    lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'
}

Personaly, I like to document the function by, at least, adding the function signature prior to the definition.

Then, I declare local parameters for each arguments and readonly parameters when I want to protect them from unexpected modification.

If the argument is mandatory, I use a special parameter expansion form:

${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.

How I would write your example:

# 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}'
}
like image 85
Damien Flament Avatar answered Sep 20 '22 06:09

Damien Flament