shell脚本使用两个横杠接收外部参数的方法
2021-02-01 04:06
1216 查看
首先,效果是这样的:
既可以处理短选项(-)又可以处理长选项(--)
[developer@hadoop-cluster-manager shell]$ ./demo.sh --help sqoop程序开始运行: demo.sh Usage: ./demo.sh [options] Options: --append, -a: 追加导入(默认为追加模式) --overwrite, -o: 覆盖导入 --method, -m: single-单日导入 interval-区间导入 all-全表导入 --date, -d: 单日导入,某一日期数据(格式为yyyymmdd) --startdate, -s: 区间导入,开始日期 --enddate, -e: 区间导入,结束日期 --help, -h 帮助
shell脚本接外部参数有一种很简单的办法,在脚本中使用$0,$1,$2...指代执行脚本时传入的第几个参数($0是脚本名)。
但是,这样做毕竟不够优雅,
另一种方法shell脚本内使用getopts命令,只可以接短选项(eg:-d,-s,-h),很方便,比较简单,可以自己去搜一搜。
但如果想要达成上面这种效果同时支持长选项和短选项(eg:--date,-d,--startdate,-s,--help,-h),
就只能使用getopt命令了:
# 定义命令执行选项 if ! ARGS=$(getopt -o aom:d:s:e:h --long append,overwrite,method:,date:,startdate:,enddate:,help -n "$0" -- "$@"); then echo "Terminating..." echo -e "Usage: ./$SCRIPT_NAME [options]\n" echo -e "Options:\n --append, -a: 追加导入(默认为追加模式)\n --overwrite, -o: 覆盖导入 \n\n --method, -m: single-单日导入\n interval-区间导入\n all-全表导入\n\n --date, -d: 单日导入,某一日期数据(格式为yyyymmdd)\n\n --startdate, -s: 区间导入,开始日期\n --enddate, -e: 区间导入,结束日期\n\n --help, -h 帮助" exit 1 fi # 将规范化后的命令行参数分配至位置参数($1,$2,...) # The -- ensures that whatever options passed in as part of the script won't get interpreted as options for set, but as options for the command denoted by the $progname variable. eval set -- "${ARGS}" # 接受执行选项;赋值给变量 while true; do case "$1" in -a|--append) mode='append' shift ;; -o|--overwrite) mode='overwrite' shift ;; -m|--method) method=$2 shift 2 ;; -d|--date) date=$2 shift 2 ;; -s|--startdate) startdate=$2 shift 2 ;; -e|--enddate) enddate=$2 shift 2 ;; --) shift break ;; -h|--help) echo -e "Usage: ./$SCRIPT_NAME [options]\n" echo -e "Options:\n --append, -a: 追加导入(默认为追加模式)\n --overwrite, -o: 覆盖导入 \n\n --method, -m: single-单日导入\n interval-区间导入\n all-全表导入\n\n --date, -d: 单日导入,某一日期数据(格式为yyyymmdd)\n\n --startdate, -s: 区间导入,开始日期\n --enddate, -e: 区间导入,结束日期\n\n --help, -h 帮助" exit 0 ;; ?) echo "missing options, pls check!" exit 1 ;; esac done
到此这篇关于shell脚本使用两个横杠接收外部参数的文章就介绍到这了,更多相关shell脚本接收参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:相关文章推荐
- 向shell或者sql脚本传参或接收参数的方法
- shell脚本中的grep命令参数使用方法介绍(转载)
- Shell使用笔记-遍历取脚本外部传入的参数
- [Android]Recovery调用外部Shell脚本,Shell脚本使用ui_print方法
- 使用getopt处理shell脚本的参数 推荐
- 使用eval命令解决shell脚本中函数嵌套调用中的参数问题
- zabbix3.0.4使用shell脚本和zabbix自带模板两种方法添加对指定进程和端口的监控
- PHP教程之PHP中shell脚本的使用方法分享
- Shell脚本中判断输入变量或者参数是否为空的方法
- [备忘]如何接收向shell脚本传入的参数
- 使用bash命令参数调试shell脚本
- ubuntu12.04中shell脚本无法使用source的原因及解决方法
- shell脚本接收来自命令行传入的参数:
- ubuntu12.04中shell脚本无法使用source的原因及解决方法
- FTP定时批量下载文件(SHELL脚本及使用方法 )
- zabbix3.0.4使用shell脚本和zabbix自带模板两种方法添加对指定进程和端口的监控
- linux使用shell脚本创建多分支判断使用function传递参数
- 使用VBS访问外部文本文件一些方法和脚本实例
- crontab中使用环境变量的方法(手动执行shell脚本可以,在定时任务中不行)
- PHP教程之PHP中shell脚本的使用方法