Search code examples
zshshzshrc

"*.foo" shell function


I want to add to my .zshrc function that will perform operations with file that has ".c" suffix. For example,

*.c () {
    gcc $0 -o ${0%.*}
}

must perform "gcc foo.c -o foo" when I am entering "foo.c"

But when I added this function to ".zshrc", my shell begins prints "no matches found: *.c" on login.

Can I do this other way or make this function "lazy"?


Solution

  • You'll want alias -s behaviour. From the manpages:

     ALIASES
       Suffix aliases are supported in zsh since version 4.2.0. Some examples:
    
           alias -s tex=vim
           alias -s html=w3m
           alias -s org=w3m
    
       Now pressing return-key after entering foobar.tex starts vim with foobar.tex. Calling
       a html-file runs browser w3m. www.zsh.org and pressing enter starts w3m with argument
       www.zsh.org.
    

    Combine your written function to a suffix alias and you should be set to go!

    First, write your function in this form:

    compile_c () {     
       gcc $1 -o ${1%.*}
    }
    

    And then the suffix alias

    alias -s c='compile_c'
    

    will work as intended.