一、下面的代码,可以通过"./getopts.sh -d 5"的方式获取参数:
1 #!/bin/sh 2 # 3 # File: getopts.sh 4 # 5 usage() { 6 7 } 8 day=7 #default value 9 if [ $# -lt 1 ]; then 10 usage 11 exit 1 12 else 13 while getopts ":d:" opt; 14 do 15 case $opt in 16 d) 17 day=$OPTARG #get the value 18 ;; 19 ?) 20 echo "How to use: $0 [-d DAY]" >&2 21 exit 1 22 ;; 23 :) 24 echo "Option -$OPTARG requires an argument." >&2 25 exit 1 26 ;; 27 esac 28 done 29 fi 30 echo $day
解释下面的部分:
1 while getopts ":d:" opt; do
第一个冒号表示忽略错误(例如出现了不认识的参数),并在脚本中通过::)来处理这样的错误;字母d则表示,接受参数-d;d后面的冒号表示 参数d接收值,即“-d 7”这样的形式;(这里opt变量,可以在while循环中引用当前找到的参数,试试输出$opt试试)
如果是要有很多参数,那么写法可能是:
1 while getopts ":ixarm:uneh" opt; do
二、
1 #! /bin/bash 2 # 测试 getopts 的用法 3 # 及与位置参数的关系 4 usage() 5 { 6 echo 'basename $0' [-x] [-y] args 7 exit 0 8 } 9 while getopts "xy:" options;do 10 case $options in 11 x) echo "you enter -x as an opton";; 12 y) echo "you ecter -y as an optin" 13 echo "\$OPTARG is $OPTARG";; 14 \?) usage;; 15 esac 16 done 17 [[ -z $1 ]] && usage 18 index=1 19 for agrs in "$@";do 20 echo \$$index: $agrs 21 (( index ++ )) 22 done