Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Bash Shell 快速入門指南:環境變數、腳本規範與 test 判斷

要把 Bash Shell 學到精通需要時間,但工作上常常得快速上手、寫幾個簡單腳本交差。如果你只是想快速掌握基本用法,下面的內容正合適;若想深入研究,還是建議買一本 shell 腳本編程的書。

先說清楚:這不是 shell 腳本編程的深入探討,而是一份語法速查手冊。

常見環境變數

· $PATH:可執行程式的搜尋路徑,類似 DOS 下的 PATH。
· $HOME:使用者家目錄。
· $MAIL:郵件投遞路徑。
· $IFS:命令行中作為字元分隔的字串,通常含空白、定位字元與換行符。查看方式:$ echo $IFS | od -bc
· PS1 與 PS2:第一與第二提示符,PS1 預設為 $,PS2 為 >。想辦法觸發 PS2:$ ls | 後按 Enter。
· $USER:登入名稱。
· $TERM:終端機類型,有些編輯器需要正確設定才能正常運作。
· $SHELL:登入時的 shell 類型。

要查看變數值,用 echo 加上 $變數名即可,例如 $ echo $USER 會輸出 ravi。

腳本編寫三規則

1)首行必須是 #!/bin/bash。井號加驚嘆號再加上 shell 路徑,告訴解析器這是 shell 腳本並指定解釋器。
2)執行前先給予執行權限:

$ chmod ugo+x your_shell_script.sh

3)以 .sh 結尾命名。這不是強制,但屬於良好慣例。

條件判斷:if

if condition_is_true
then
    execute commands
else
    execute commands
fi

有多個條件時可用 elif 形成分支:

if condition_is_true
then
    execute commands
elif another_condition_is_true
then
    execute commands
else
    execute commands
fi

實際例子:

if grep "linuxhelp" thisfile.html
then
    echo "Found the word in the file"
else
    echo "Sorry no luck!"
fi

if 的搭檔:test 指令

test 是 shell 內建指令,對右側運算元進行判斷並傳回 true 或 false。

關系運算

-eq   等於
-ne   不等於
-lt   小於
-gt   大於
-le   小於等於
-ge   大於等於

檔案測試

-f file   存在且為一般檔案
-r file   存在且可讀
-w file   存在且可寫
-x file   存在且可執行
-d file   為目錄
-s file   存在且不為空

字串測試

-n str        字串非空為真
-z str        字串為空為真
str1 == str2  兩字串相等為真
str1 != str2  兩字串不相等為真
str           已賦非空值為真
Copyright © Linux教程網 All Rights Reserved