使用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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值