shell支持選項引數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
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/197126.html
標籤:其他
上一篇:在Linux作業系統下如何創建eclipse快捷方式
下一篇:kvm虛擬化安裝部署(命令列/最小化),kvm虛擬化平臺搭建,kvm虛擬化技術實戰,詳解+易錯點攻破~~%+++
