shell脚本接参数优美用法
学习 bash
shell脚本接参数优美用法
2.1 getopt命令的用法
2.2 示例
1. 示例脚本
2. 转载阅读
1. 示例脚本
#!/usr/bin/env bash
args="$*"
function usage(){ echo "Usage: `basename $0` options (-h HOST|-n NAME)" }
check(){ "check" }
if [ $# -lt 4 ] then usage exit 55 fi
while getopts ":h:n:" Option;do case $Option in h) host=$OPTARG ;; n) name=$OPTARG ;; *) usage ;; esac done
shift $(($OPTIND - 1))
check
exit 0
2. 转载阅读
转载阅读:shell中的getopt与getopts
在shell脚本之shift和getopts篇中有提到getopts,除了bash自带的内部变量getopts外,util-linux-ng包还提供了一个工具getopt ,该工具较bash内置的getopts更强大,其不仅支持短参-s,还支持?Clongopt的长参数,甚至支持-longopt的简化参数。相较于getopts ,getopt 不但支持长短选项,其还支持选项和参数放在一起写。
2.1 getopt命令的用法
getopt [options] -o|?Coptions optstring [options] [?C] parameters 选项说明:
-a:使getopt长参数支持”-“符号打头,必须与-l同时使用
-l:后面接getopt支持长参数列表
-n program:如果getopt处理参数返回错误,会指出是谁处理的这个错误,这个在调用多个脚本时,很有用
-o:后面接短参数列表,这种用法与getopts类似
-u:不给参数列表加引号,默认是加引号的(不使用-u选项),例如在加不引号的时候 ?Clongoption “arg1 arg2” ,只会取到”arg1”,而不是完整的”arg1 arg2”
其有两种使用方法,如下
方法1:
ARGV=($(getopt -o 短选项1[:]短选项2[:]...[:]短选项n -l 长选项1,长选项2,...,长选项n -- "$@")) for((i = 0; i < ${#ARGV[@]}; i++)) { eval opt=${ARGV[$i]} case $opt in -短选项1|--长选项1) process ;; -短选项2|--长选项2) ((i++)); eval opt=${ARGV[$i]} ;; ... -短选项n|--长选项n) process ;; --) break ;; esac }
方法2:
$@")) eval set -- $ARGV" while true do case $1" in -短选项1|--长选项1) process shift ;; -短选项2|--长选项2) opt = $2 process shift 2 ;; ...... -短选项3|--长选项3) process ;; --) break ;; esac }
注意:如果getopt命令本身没有使用-o|?Coption选项的话,那么?C后面的第一个参数被当做短选项。
2.2 示例
#!/bin/bash
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: -n 'example.bash' -- $@"` if [ $? != 0 ] ; then "Terminating..." >&2 ; exit 1 ; fi
$TEMP" true ; do in -a|--a-long) "Option a" ; shift ;; -b|--b-long) "Option b,argument `$2'" ; shift 2 ;; -c|--c-long) $2" in "") "Option c,no argument"; shift 2 ;; *) shift 2 ;; esac ;; --) shift ; break ;; *) "Internal error!" ; exit 1 ;; done "Remaining arguments:" for arg do '--> '"`$arg'" ; done
运行结果如下:
[root@test bash]# sh get.sh -a par1 'another arg' --c-long 'wow!*?' -cmore -b " very long " Option a Option c,no argument Option c,argument `more' Option b,argument ` very long ' Remaining arguments: --> `par1' --> `another arg' --> `wow!*?'
使用eval 的目的是为了防止参数中有shell命令,被错误的扩展。
平时使用时,可以使用的样例为:
ARGS=`getopt -a -o I:D:T:e:k:LMSsth -l instence:,database:,table:,excute:,key:,list,master,slave,status,tableview,help -- $@"` [ $? -ne 0 ] && usage
${ARGS}" in -I|--instence) instence=$2" shift ;; -D|--database) database=shift ;; -T|--table) table=shift ;; -e|--excute) excute="yes" shift ;; -k|--key) key=shift ;; -L|--list) LIST="yes" ;; -M|--master) MASTER="yes" ;; -S|--slave) SLAVE="yes" ;; -A|--alldb) ALLDB="yes" ;; -s|--status) STATUS="yes" ;; -t|--tableview) TABLEVIEW="yes" ;; -h|--help) usage ;; --) shift break ;; esac shift done (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|