Shell Script : Jekyll Markdown Generator

很多人都問我說為什麼要用 MAC?除了做工精良,續航力高,還有一點非常棒的就是他可以和 Linux 共用大部分的 Unix Script。以下就用一個小小的例子來解釋能寫一些簡單的 Script 可以讓工程師一天過的更愉快。

一開始的緣由在於 Jekyll 的 Markdown 有一個既定的格式,就是檔名要是 日期-標題.md 並且內部要以特定的 tag ,不過如果每次發一篇文章都還要去填寫日期的話,並修改檔名的話,就顯得太費工夫了,所以初始的概念就是能 input titletag , 然後剩下重複的格式就交由 Script。

I/O

所以首先就先做簡單 I/O 來得到 titletag

First of all, we should handle some I/O to get the input arguments title and tag .

printf "Title : "
read title
printf "Tags : "
read tags

Parse

再來由於我們要直接把 title 拿來當做檔名,不過由於其中多少會有一些標點符號,在這裡我們就要先把他們移除。所以我們用 sed 來做取代的動作,由於 sed 支援正規表示,所以我們可以用 [[:punct:]] 來指定標點符號,若之後有延伸的取代動作的話可以參考這裡更多正規表示。

Next, since there will be some punctuations in the title (e.g. .,;/?), we should remove them before we use it as part of the filename later. Here, we are using sed to remove the punctuations. Fortunately, sed support regular expression, so we can use [[:punct:]] to represent the punctuations and remove them. You could find more regular expression here , if we want to do more extensions.

parse=`echo $title | sed -e "s/[[:punct:]]//g"`

最後再把空白都換成一槓。 Also, we do the same handling to the space, but this time we replace it with -.

parse=`echo $parse | sed -e "s/ /-/g"`

Date

再來我們要取得 Post 當下的時間,把它加到檔名裡,這裡使用 date 來取得時間並且用內建輸出syntax 。這裡列舉一些簡單的表示方式。

We also need to get the time as the create time when we lunch the script. We use date to get then current time, and since it supports output format , we can simply transform the date to the format we want. Here is a handy lookup table.

Example Format Outcome
年(year) %Y 2016
月(month) %m 03
日(day) %d 07
時(hour) %H 16
分(minute) %M 12
秒(second) %S 00

如此我們可以把現在時間轉成我們要的格式。

# 2016-03-07
create_date=`date +"%Y-%m-%d"`
# 2016-03-07 22:56:00
create_date_time=`date +"%Y-%m-%d %H:%M:%S"`

Demo

最後展示一下使用的情況

Here is the screenshot.

> sh auto_post.sh
  Title : Shell Script : Jekyll Markdown Generator
  Tags : code
> ls _posts/
  2016-03-07-Shell-Script-Jekyll-Markdown-Generator.md
> cat _posts/2016-03-07-Shell-Script-Jekyll-Markdown-Generator.md
  ---
  layout : post
  cover: false
  title: 'Shell Script : Jekyll Markdown Generator'
  date: '2016-03-07 22:56:00'
  tags: code
  subclass: 'post tag-code'
  categories: ''
  cover: ''
  ---

Source Code

由於不同得 template 會有不同 Front Matter , 所以可以自行視需求多加argument 進去,不過作法是雷同的。可以從這裡拿到原始碼。

Since different Jekyll template has different Front Matter, feel free to add more arguments in the script to make it compatible to your Jekyll template. You can find the Source code here.