最近学习了一下getopt(不是getopts)命令来处理执行shell脚本传入的参数,在此记录一下,包括长选项、短选项、以及选项的值出现的空格问题,最后写了个小的脚本来处理输入的参数
首先新建一个test.sh来测试
test.sh内容
#! /bin/sh
echo `getopt a:b::c "$@"`
运行
sh test.sh -a 1 -b2 -c 3 4
结果
-a 1 -b 2 -c -- 3 4
test.sh内容
#! /bin/sh
echo `getopt -o a:b::c -l along:,blong::,clong -- "$@"`
运行
sh test.sh -a 1 -b2 -c 3 4
结果
-a ‘1‘ -b ‘2‘ -c -- ‘3‘ ‘4‘
具体什么时候带 -- 看getopt的help说明
Usage:
getopt <optstring> <parameters>
getopt [options] [--] <optstring> <parameters>
getopt [options] -o|--options <optstring> [options] [--] <parameters>
运行
sh test.sh --along=1 --blong=2 --clong
结果
--along ‘1‘ --blong ‘2‘ --clong --
"$@"需要带双引号,不带会识别出错
test.sh内容和上面一致
#! /bin/sh
echo `getopt -o a:b::c -l along:,blong::,clong -- "$@"`
运行
sh test.sh -a 1 -b2020-01-08 15:00:00 -c 3 4
结果
-a ‘1‘ -b ‘2020-01-08‘ -c -- ‘15:00:00‘ ‘3‘ ‘4‘
运行
sh test.sh -a 1 -b"2020-01-08 15:00:00 "-c 3 4
结果
-a ‘1‘ -b ‘2020-01-08 15:00:00 -c‘ -- ‘3‘ ‘4‘
与短选项相同
运行
sh test.sh --along=12 --blong="2020-01-08 15:00:00" --clong
结果
--along ‘12‘ --blong ‘2020-01-08 15:00:00‘ --clong --
下面这个脚本是将输入的参数赋值到具体变量上去
#! /bin/sh
ARGS=`getopt -o a:b::c -l along:,blong::,clong -- "$@"`
#getopt是否执行成功
if [[ $? -ne 0 ]]
then exit 1
fi
#处理空格,不加eval会将2020-01-08 15:00:00分到两个位置参数上
eval set -- "${ARGS}"
while [[ -n "$1" ]]
do
case "$1" in
-a|--along)
along=$2
shift 2
;;
-b|--blong)
case "$2" in
"")
#指定个默认值吧
blong=false
shift 2
;;
*)
blong=$2
shift 2
;;
esac
;;
-c|--clong)
echo "option c 无参数"
shift
;;
--)
shift
break
;;
*)
echo "ERROR OPTION!"
exit 1
;;
esac
done
args="args: along:\"${along}\",blong:\"${blong}\""
echo ${args}
运行
sh test.sh --along=1 --blong="123" --clong
结果
option c 无参数 args: along:"1",blong:"123"
以上就是整理的getopt命令的内容,如果有错误的地方还请指正
参考:
http://yejinxin.github.io/parse-shell-options-with-getopt-command
原文:https://www.cnblogs.com/ielgnahz/p/12168150.html