Bash 腳本是最不需要成本的自動化工具。以下從零開始,走完一支腳本從建立、執行到互動的完整流程。
cat /etc/shells
輸出的清單就是這台機器上可用的 shell,最常見的是 /bin/bash 與 /bin/sh。
建立 firstscript,內容如下:
#! /bin/bash # This is a test. echo -n Your current directory is: pwd echo $HOME echo Your current directory is: pwd # END.
第一行 #! 開頭的是 shebang,用來告訴系統該用哪個直譯器執行;以 # 開頭的是註解,不會被執行。
/bin/bash firstscript
若跳「找不到檔案」,先用 pwd 確認自己所在目錄,再帶完整路徑執行:
/bin/bash /home/user/firstscript
chmod a+x firstscript ./firstscript
加上執行權後,用 ./ 前綴就能直接跑。這裡的 ./ 代表「當前目錄」,是安全機制:Linux 預設不把當前目錄放進 PATH,避免在別人的目錄誤執行同名程式。
#!/bin/sh
echo -n Please input your ID:
read id_var
echo -n Please input your password:
read passWord
echo User ID = $id_var
echo password = $passWord
if [ $passWord = "admin" ]; then
echo "password is right"
else
echo "password is wrong"
fi
read 會把使用者輸入存進變數,$ 前綴用來取值,if ... then ... else ... fi 是標準的條件結構。注意 [ 與 ] 兩側以及運算子前後都要留空格,這是新手最常踩的語法地雷。
存檔後一樣用 chmod a+x 加上執行權,再執行看看,你就有第一支會問你問題的腳本了。