シェルはオプションパラメータgetopts / getoptをサポートします

シェルはオプションパラメータ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

動作結果:
ここに写真の説明を挿入

おすすめ

転載: blog.csdn.net/it_chang/article/details/109382927