Search code examples
macoszshoh-my-zsh

How to create a suffix alias for files without an extension?


I just found about zsh suffix aliases that allow one to associate a program with an extension in the shell:

alias -s {md,txt}=nano

Is there a way to do something like this but for file that do not have an extension?

I've tried:

alias -s {}=nano

But if I then try to use it, I get a command not found error:

> alias -s {}=nano
> touch file_without_extension
> file_without_extension
zsh: command not found: file_without_extension

Solution

  • Suffix aliases require a filename extension. You can use a command_not_found_handler function to work around that, though:

    # Run this from a zsh prompt or put it in a file and source it
    command_not_found_handler() {
        # If just the name of an existing file is given, with no extra arguments
        # open it in nano. Otherwise, print a message to stderr and return an error.
        if [[ $# -eq 1 && -f $1 ]]; then
            nano "$1"
        else
            print -u2 -f "command not found: %s\n" "$1"
            return 127
        fi
    }
    # Then with the function loaded:
    $ file_without_extension # Opens in nano
    $ file_that_doesnt_exist
    command not found: file_that_doesnt_exist
    $ file_without_extension blah
    command not found: file_without_extension