how to call zsh custom function with parameters

Viewed 894

I have a function that executes a shell command--ls in this case--without use of the return key.

hotkey_ls () { echo; ls; zle redisplay }                                             
zle -N hotkey_ls                                                                      
bindkey ',f' hotkey_ls

I'd like to be able to pass the shell command as a parameter, i.e. bindkey ',a' hotkey_ls('ls -a')

2 Answers

The parenthesis in the function invocation which you wrote in your post don't make sense, but otherwise, you can replace the ls by eval ${1:-ls} inside the function, to achieve what you want.

Don't forget to quote your invocation, i.e.

bindkey ,f 'hotkey_ls "ls -a"'

Depending on how much readability you are ready to sacrifice for fewer lines of code, one possibility is to do the following (1 LoC + 3 LoC per item):

hotkey_cmd() { local cmd=$1; echo; eval "$cmd"; zle redisplay }                                             

hotkey_ls() { hotkey_cmd "ls" }
hotkey_ls_a() { hotkey_cmd "ls -a" }
hotkey_git_status() { hotkey_cmd "git status" }

zle -N hotkey_ls
bindkey ',f' hotkey_ls
zle -N hotkey_ls_a
bindkey ',a' hotkey_ls_a
zle -N hotkey_git_status
bindkey ',gs' hotkey_git_status

Or do this (9 LoC + 0 LoC per item):

hotkey_cmd() { local cmd=$1; echo; eval "$cmd"; zle redisplay }                                             

declare -A mappings=(f "ls" a "ls -a" gs "git status")
for shortcut cmd in ${(kv)mappings}; do
    function_name="hotkey_${cmd//[^a-z]/_}"  # e.g. hotkey_ls__a
    echo "$function_name"
    eval "${function_name}() { hotkey_cmd \"$cmd\" }"
    zle -N "$function_name"
    bindkey ",$shortcut" "$function_name"
done
Related