2020年11月17日 星期二

shell script 帶參數, 印出usage使用方式的程式框架

 撰寫Script常常會帶入參數,又需要當使用者沒有帶入參數時,要印出使用方法.

下面的程式框架是要求使用者帶入兩個參數,如果使用錯誤,則印出usage()告知使用者.

此檔案 test.sh實際做法如下:

#!/bin/sh

function usage()

{

    echo "test.sh.sh [arg1] [arg2]"

    echo "ex: test.sh 1 2"

}

if [ "$#" -lt "2" ]; then

    usage

    exit 0

fi

#If arg1 and arg2 exist, then do following thing...