萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux Shell 腳本入門:查看可用 Shell、撰寫第一支腳本、變數與互動、執行權限

1. 查看系統支援的 Shell

cat /etc/shells

2. 撰寫第一支腳本 firstscript

#!/bin/bash
# This is a test.
echo -n "Your current directory is: "
pwd
echo $HOME
echo "Your current directory is: "
pwd
# END.

3. 執行腳本的兩種方式

  • 指定解譯器執行:/bin/bash firstscript (若找不到檔案,先用 pwd 確認路徑,再用 /bin/bash $(pwd)/firstscript)
  • 賦予執行權限直接執行:
    chmod a+x firstscript
    ./firstscript

4. 互動式腳本範例:密碼驗證

#!/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 讀取使用者輸入至變數;[ ... ] 條件判斷兩側需有空格;變數引用建議加雙引號避免空值錯誤。

copyright © 萬盛學電腦網 all rights reserved