使用getopt命令規範shell腳本的命令行選項

#!/bin/bash

log()
{
    msg=$1
    time=$(date "+%Y-%m-%d %H:%M:%S" )
	echo "${time}|${msg}"
}

usage()
{
cat <<EOF
Usage:smallskill.sh [OPTION]...
Mandatory arguments to long options are mandatory for short options too.
-e,--examination    Send examination(test) massages
-x,--exclude    Exclude build folder,use ';' to seperate
EOF
}

#-o或--options選項後面接可接受的短選項,如ex:s::,表示可接受的短選項爲-e -x -s,其中-e選項不接參數,-x選項後必須接參數,-s選項的參數爲可選的
#-l或--long選項後面接可接受的長選項,用逗號分開,冒號的意義同短選項。
#-n選項後接選項解析錯誤時提示的腳本名字["std.sh: unknown option -- d"]
ARGS=$(getopt -a -o e:x:s: -l examination:,exclude:,srcdir: -n "smallskill.sh" -- "$@")

#如果參數不正確,打印提示信息
[[ $? -ne 0 ]] && usage && exit 1

echo ${ARGS}
#將規範化後的命令行參數分配至位置參數($1,$2,...)
eval set -- "${ARGS}"
while true
do
    case "$1" in
	    -e|--examination)
		    export TEST_MSG="$2"
			shift 
			log "this is a test message! ${TEST_MSG}"
			;;
	    -x|--exclude)
		    excludedir="$2"
			shift 
			;;
		-s|--srcdir)
		    srcdir="$2"
			shift 
			;;
		--)
		    shift
		    break
		  ;;
	esac
	shift		
done

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章