shell支持选项参数getopts/getopt

shell支持选项参数getopts/getopt

getopts
#!/bin/bash

function func1(){
	echo "这是func1 -c $1"
}

function func2(){
	echo "这是func2 -a $1"
}

function func_help(){
	echo -e "usage:\t-h\thelp"
	echo -e "\t-c\tconf file"
	echo -e "\t-a\taction"
}

# getopts 不支持长选项
# 选项后接 : 参数必选
# $OPTARG getopts 内置变量,接收选项后的参数
while getopts ":a:c:h" opt
do
	case $opt in
		h)
			func_help
			;;
		c)
			func1 $OPTARG
			;;
		a)
			func2 $OPTARG
			;;
		:)
			echo "This option -$OPTARG requires an argument."
			exit 1
			;;
		?)
			echo "-$OPTARG is not an option."
			exit 2
			;;
	esac
done

getopt
#!/bin/bash

# getopt 需要和 set 配合使用
# getopt 支持长选项
# 选项后接: 参数必选
# 选项后接:: 参数可以一个或零个,分两个情况讨论:
	# 1。使用短选项:接多个参数时必须紧贴选项,eg: -mtest1
	# 2。使用长选项:必须用=号连接,eg: --more=test1
TEMP=$(getopt -o a:c:m::h --long action:,config:,more::,help -n "command" -- "$@")
# 选项解释:
# -o     短选项
# --long 长选项,必须和 -o 选项一一对应
# -n     出错时的信息
# --     强制使用原始字符, eg: -- -a (-a就不会当做选项)
# $@     参数本身列表

if [ $? != 0 ]; then echo "Terminating..." >&2; exit 1; fi

eval set -- "$TEMP"

function func1(){
	echo "这是func1,接收选项 -c 参数为:$1"
}

function func2(){
	echo "这是func2,接收选项 -a 参数为:$1"
}

function func3(){
	echo "这是func3,接收选项 -m 参数为:$1"
}

function func4(){
	echo "这是func4,接收原始字符参数 -- 参数为:$1"
}

function func_help(){
	echo -e "usage:\t-h|--help\thelp"
	echo -e "\t-c|--config\tconf file"
	echo -e "\t-a|--action\taction"
	echo -e "\t-m|--more\tmore args"
}


while :
do
	case $1 in
		-h|--help)
			func_help
			shift
			;;
		-c|--config)
			func1 $2
			shift 2
			;;
		-a|--action)
			func2 $2
			shift 2
			;;
		-m|--more)
			case "$2" in
				"")
					echo "Option m, no argument"
					shift 2
					;;
				*)
					func3 $2
					shift 2
					;;
			esac
			;;
		--)
			shift
			break
			;;
		*)
			echo "Error!."
			exit 1
			;;
	esac
done

for arg do
	func4 $arg
done

运行结果:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值