Search code examples
shellterminalauto-generateshebang

Using `touch` command, recognize file type and auto-generate shebang?


So, I really like the fact that text editors such as Vim allows you to auto-write text (most of the times shebangs) when creating a new file with a specific file extension.

However, I'd like to know if there's any way to do it from the terminal using the touch command.

For example, I want to auto-generate shebangs for my Python script I just created from the terminal, like below:

$ touch test.py                   # create file and auto-generate
$ cat test.py                     # see the contents to confirm
#!/usr/bin/env python
# -*- coding: utf-8 -*-

I know I can just create a bunch of auto-generating text variables in my environment such as PY_SHEBANG="#\!/usr/bin/env python\n# -*- coding: utf-8 -*-" and just do:

$ echo $PY_SHEBANG > file.py

But the thought of going through so much trouble just messes with my head.

That being said: is there any way to configure the terminal/shell so that it can recognize the filetype of the file I'm creating, and append text to it automatically based on filetype, with a single touch command?

NOTE: I am using zsh and oh-my-zsh.


Solution

  • Sure you can. Simply use aliases and substitute touch for a function we write ourselves. However I would propose using the alias etouch (enhanced touch) so if you decide to use the touch command normally, you can.

    Since you are using zsh, it makes things even easier (but I'd imagine it'd be similar for bash) In your .zshrc (or .bashrc, I wouldn't exactly know), write a function that checks the filetype and inputs whatever, like the one below:

    # function for auto-generating shebang
    function enhanced_touch () {
        if [ -f $1 ]; then
           echo "$1 already exists"
           return 0
        fi
        if [[ $(echo -n "$1" | tail -c 3) == ".py" ]]; then
            echo "#!/usr/bin/env python\n# -*- coding: utf-8 -*-" > $1
        else
            touch $1
        fi
    }
    
    alias etouch="enhanced_touch"
    

    Obviously, I have only customized the function for recognizing python files just as you requested. But I'll leave the other filetypes for you to write.

    Also, don't forget to source .zshrc. Good luck!