為shell script設定參數

通常 shell script是互動性的,這意味著它們接受來自用戶的命令作為輸入並執行它們。這邊我們提供兩種為 shell script設定參數的方式。

字元參數:

func(){
    echo "Usage:"
    echo "    flag.sh [-a something] [-b something] [-c]"
    exit 0
}

# if ":" following a latter, you should give a value.
# if ":" is the first latter, all error will be ignore.
while getopts ":a:b:c" argv
do
    case $argv in
    a)
        VAR1=$OPTARG
        echo "a=$VAR1"
        exit 0
        ;;
    b)
        VAR2=$OPTARG
        echo "b=$VAR2"
        exit 0
        ;;
    c)
        echo "'c' command be called"
        exit 0
        ;;
    
    ?)
        func
        ;;
    esac
done
func
exit 0

單詞參數:

func(){
    echo "Usage:"
    echo "     sh parameter.sh [--arg_1=something] [--p_out=something]"
    exit 0
}

while [ $# -gt 0 ]; do
  case "$1" in
    --p_out=*)
      p_out="${1#*=}"
      ;;
    --arg_1=*)
      arg_1="${1#*=}"
      ;;
    *)
      func
      exit 1
  esac
  shift
done
echo "p_out=$p_out"
echo "arg_1=$arg_1"

Add a Comment

發佈留言必須填寫的電子郵件地址不會公開。