next up previous contents
Next: 實機練習題 Up: Shell Scripts Previous: 追蹤與除錯   Contents

腳本預設參數

  1. Shell 腳本執行時參數的預設變數為 $0, $1, $2,...,對應如下:
    /path/to/scriptname  opt1  opt2  opt3  opt4  ...
           $0             $1    $2    $3    $4   ...
    
  2. sh04.sh 列出執行命令名稱、前三個參數:
    [dywang@dywmac zzz]$ cat sh04.sh
    #!/bin/bash
    echo "The script name is ==> $0"
    [ -n "$1" ] && echo "The 1st paramter is ==> $1" || exit 0
    [ -n "$2" ] && echo "The 2nd paramter is ==> $2" || exit 0
    [ -n "$3" ] && echo "The 3th paramter is ==> $3" || exit 0
    
  3. 執行 sh04.sh 加三個參數,列出執行命令名稱及三個參數:
    [dywang@dywmac zzz]$ sh sh04.sh abc 123 cde
    The script name is ==> sh04.sh
    The 1st paramter is ==> abc
    The 2nd paramter is ==> 123
    The 3th paramter is ==> cde
    
  4. 執行 sh04.sh 加兩個參數,列出執行命令名稱及兩個參數後退出腳本。
    [dywang@dywmac zzz]$ sh sh04.sh abc 123
    The script name is ==> sh04.sh
    The 1st paramter is ==> abc
    The 2nd paramter is ==> 123
    



De-Yu Wang 2019-08-12