你的第一個 Bash 指令稿

Bash 指令稿入門

Alex Scriven

Data Scientist

Bash 指令稿結構

一個 Bash 指令稿有幾個關鍵特徵:

  • 通常以 #!/usr/bash 開頭(獨立一行)
    • 讓直譯器知道這是 Bash 指令稿,並使用位於 /usr/bash 的 Bash
    • 若你把 Bash 安裝在別處,例如 /bin/bash,路徑可能不同(可輸入 which bash 檢查)
  • 中間的行放置程式碼
    • 可以是逐行指令或程式設計結構
Bash 指令稿入門

Bash 指令稿結構

如何儲存與執行:

  • 副檔名為 .sh
    • 若首行已有 she-bang 與 Bash 路徑(#!/usr/bash)技術上可省略,但仍是慣例
  • 可在終端機用 bash script_name.sh 執行
    • 或者若有首行(#!/usr/bash),可直接用 ./script_name.sh 執行
Bash 指令稿入門

Bash 指令稿範例

完整指令稿範例(名為 eg.sh):

#!/usr/bash
echo "Hello world"
echo "Goodbye world"

可用 ./eg.sh 執行,輸出如下:

Hello world
Goodbye world
Bash 指令稿入門

Bash 與 shell 指令

Bash 指令稿中的每一行都可以是 shell 指令。

因此,你也可以在 Bash 指令稿中使用 pipe。

考慮一個文字檔(animals.txt

magpie, bird
emu, bird
kangaroo, marsupial
wallaby, marsupial
shark, fish

我們要計算各群的動物數量。

Bash 指令稿入門

Bash 與 shell 指令

在 shell 中你可以在終端機串接多個指令。改成放進一個指令稿(group.sh):

#!/usr/bash
cat animals.txt | cut -d " " -f 2 | sort | uniq -c

現在(儲存指令稿後)執行 bash group.sh 會得到:

   2 bird
   1 fish
   2 marsupial
Bash 指令稿入門

一起來練習吧!

Bash 指令稿入門

Preparing Video For Download...