Customizing Your Commands In Zsh to Create Ad-Hoc Interfaces

This is a slick little set of tricks I use constantly. Take systemctl for example. This command is notorious for its verbose syntax. One simplistic way to cut down on all that extra typing is to use an alias, e.g.:

alias syr='systemctl restart'
alias syt='systemctl status'

Or better, make a function, e.g. for find and its awful syntax:

function find_mod() {
    find $2 -iname $1
}

Functions can really enhance your commands.

function find_mod() {
    find $2 -iname $1 |sort -n -r | less
    echo 'found yo shit playa'
}

Maybe add a super short alias to top it off if you don’t have it bound elsewhere…:

alias f='find_mod'

Dope. But back to systemctl. It has a lot of options. Usually when I’m using this command, I’m using only that command for a while, or at least I have a terminal dedicated to the task. So for my last trick, I present this little spell:

function precmd() { print -z  "systemctl " }

precmd is a special builtin hook function that runs after the command prompt. Hooks in zsh are pretty powerful in there own right, and I encourage you to check out the other builtins. In this case, I’m dropping “systemctl " on each new command prompt, like a prefix. The result is a sort of special REPL mode just for systemctl, so you just type whatever command your after. This would work of course for any command, so let’s abstract it as such:

function mkmode() {
    #store the input command for when this is called later
    mkmode_cmd=$1
    function precmd() { print -z "$mkmode_cmd " }
}
function rmmode() {
    function precmd() {}
}

A voila! An ad-hoc interface mode for any command. These are really just building blocks of course, play around with it, lmk what you come up with. And enjoy.