A custom shell command to create a template file

The article shows how to define a custom shell command to create a file with predefined multiple-line content. In the following example we use a custom command mdnew file-name to create a markdown file with predefined YAML front matter.

For a quick view, here is the effect:

# Create a new makrdown file hello-markdown.md with predefined YAML fonter matter
$ mdnew hello-markdown

# Show the contents of the newly created markdown file
$ cat hello-markdown.md
       │ File: hello-markdown.md
   1   │ ---
   2   │ title: hello markdown
   3   │ author: John
   4   │ date: 2023-04-11 16:48:39
   5   │ tags_input:
   6   │   -
   7   │ categories:
   8   │   -
   9   │ description: 
  10   │ ---
  11   │ 

If you are working on Windows, we suggest you use a Unix style terminal for better productivity. If you are using Git, you already have one. Git bash is a good choice for such terminals.

Here we take Git bash for example to define the custom command mdnew.

Open ~/.bash_profile or ~/.bashrc, append below content to the end of the file:

mdnew() {

    # Replace all '-' to ' ' to make it a proper title
    title="${title//-/ }"

title: $title
author: John
date: $(date +"%Y-%m-%d %H:%M:%S")
    echo "$lines" > $file_name

If you want to avoid the mdnew command to overrides an existing file by accident, you can cange the last line to:

     echo "$lines" >> $file_name

Then the command only append the YAML front matter to the file.

Then you can open Git bash and create a new markdown file like we have done above. If you have a Git bash terminal opened already, run below source command to make our custom mdnew to take effect before use it.

$ source ~/.bash_profile

# Then you can use 'mdnew' command to create a file
$ mdnew hello-markdown