如何將command lines 組合成shell script

Converting One-Liners into Shell Scripts

有時候在command line中會有些操作步驟是共通會使用的,這時候就可以把它們寫到shell scripts中(雖然減輕工作負擔的關鍵是你如何挑選要轉化成shell scripts的one-liners,這部分就要靠經驗了!)

主要步驟有六步:

  1. 將command line 寫入到file中
  2. 寫入執行權限(execute permissions)
  3. 定義shebang(直譯器的讀取參數,詳見維基),就是執行時告訴系統要用什麼直譯器去讀去。
  4. 去掉command line中固定的input 指向
  5. 添加可以修改的參數
  6. 將此shell script的位置放入環境裡的PATH

 

第一步驟:將command lines寫入成.sh 的檔案

$ vi top_words.sh

———- 按 i 進入編輯模式,結束後按est 然後輸入:wq存檔離開—–

$curl -s https://zh.wikipedia.org/wiki/Shebang |
$tr ‘[upper:]"[:lower:]’ |grep -oE  ‘\w+’|sort|uniq -c |
$sort -nr |head -n 10

第二步驟:修改此檔案的權限

chmod u+x top_words.sh

解釋: chmod   代表我們想要修改此檔案的使用權限細節
+              代表我們想要添加permission
u              代表我們要添加的permission是關於此檔案的讀取

小技巧,在我們使用 $ ls -l 時,通常會顯示當下目錄中的檔案細節如下:

$ls -l
-rw-rw-r– 1 weiting weiting 132 Jul 20 17:20 top_word.sh

最左邊的-rw-rw-r– 就代表此檔案的使用權限,此時是沒有關於讀取的權限。

第三步驟:定義此shell scripts的shebang

shebang通常就是在scripts的第一行,告訴系統要用什麼樣的直譯器來執行此scripts,此時我們要使用unix的bash (在linux中最常見的內建default 直譯器)

#!/usr/bin/env bash
$curl -s https://zh.wikipedia.org/wiki/Shebang |
$tr ‘[upper:]"[:lower:]’ |grep -oE  ‘\w+’|sort|uniq -c |
$sort -nr |head -n 10

小知識:其實shebang這個字是she+bang組合而成的,she其實就是hash(等於#)的意思,而bang則是exclamation mark

第四部:移除固定的input指向

#!/usr/bin/env bash
$curl -s https://zh.wikipedia.org/wiki/Shebang
$tr ‘[upper:]"[:lower:]’ |grep -oE  ‘\w+’|sort|uniq -c |
$sort -nr |head -n 10

第五步驟:添加參數

#!/usr/bin/env bash
NUM_WORD="$1″

$curl -s https://zh.wikipedia.org/wiki/Shebang
$tr ‘[upper:]"[:lower:]’ |grep -oE  ‘\w+’|sort|uniq -c |
$sort -nr |head -n $NUM_WORD

$1 代表的是在command line中位置於輸入第一個的參數

第六步驟:將此shell script的位置放入環境裡的PATH

使用$ls -a 來看家目錄下的.bashrc 或是.bash_profile,將你的scripts所在位置放入其中

$ export PATH$="your script directory:$PATH"

這樣就大功告成了!可以在任何地方執行你的scipts,如此便能減少很多重複工作!

 

reference:Jeroen JanssensData Science at the Command Line , Chapter 4
(強力推薦)

對「如何將command lines 組合成shell script」的一則回應

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com 標誌

您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 /  變更 )

連結到 %s