2013年4月16日 星期二

shell script 中的 getopt & getopts

在 linux shell 中我們常常用到 傳入一些參數 . 之前我都使用 getopts 的方式, 使用上都好好的 , example file 如下(片段):


while getopts ":O:h" opt; do
        echo "opt:${opt}"
        case ${opt} in
        ## ---- output size setting.
            O )
                OUT_BLOCK_SZ=${OPTARG}
            ;;

        ## ---- help menu.
            \? | h )
                ${MKMATE} color -fred "## Bad command ${OPTARG}...."
                Usage
                return 1
            ;;

        esac

    done


今天想要輸入 一堆其它的值 例如: <$> foo.sh -O 1234 dir_1 dir_2 dir_3. or
<$> foo.sh dir_1 dir_2 dir_3 ..... -O 1234
使用之前就的方式卻出問題, 這些 dir 訊息沒有辦法取出(maybe I got some mistake in getopts ),所以就換成使用 getopt 了, example 如下:


    args=`getopt O:h $@ `
    if [ $? != 0 ];then
        ${MKMATE} color -fred "## Bad command ${OPTARG}...."
        return 1
    fi

    set -- ${args}

    while [ -n "$1" ]
    do
        case $1 in

        ## ---- output size setting.
            -O )
                shift
                OUT_BLOCK_SZ=$1
            ;;

            -h | - )
                Usage
                return 1
            ;;

            \? )
                ${MKMATE} color -fred "## Bad command ${OPTARG}...."
                Usage
                return 1
            ;;

            -- )
                DIR_LIST=
            ;;

            * )
                if [ -z ${DIR_LIST} ];then
                    DIR_LIST="$1"
                else
                    DIR_LIST=${DIR_LIST}:$1
                fi

            ;;
        esac
        shift
    done


不管輸入方式是 <$>foo.sh -O 1234 dir_1 ..... or <$>foo.sh dir_1 ..... -O 1234
最後 srgs 都會 -O 1234 -- dir_1 dir_2 .....
接著用 set -- ${args} 就可以重新設定 $@ 參數 .
在利用 while 和 shift 就可以逐一取出想要的參數 , 利用 -- 當區隔就可以將 dir_1 dir_2 取入 .

我利用 : 將這些 dir 資料並起來, 有利於我的處理需求 !!



Reference :

http://changyy.pixnet.net/blog/post/25660234-%5Bbash%5D-%E5%B0%87%E6%AA%94%E6%A1%88%E5%85%A7%E7%9A%84%E5%AD%97%E4%B8%B2%E9%80%B2%E8%A1%8C%E5%8F%96%E4%BB%A3

沒有留言:

張貼留言