while [ $# -gt 0 ];do
case $1 in
-d)
shift
file_to_trash=$1
trash $file_to_trash # trash is a function
;;
-l)
print_trashed_file # print_trashed_file is a function
;;
-b)
shift
file_to_untrash=$1
untrash $file_to_untrash # untrash is a function
;;
-c)
clean_all # clean all is a function
;;
-h)
usage
exit 0
;;
\?)
usage
exit 1
;;
esacdone
i=1
while [ $i -le $# ];do
case ${!i} in
-d)
i=$(expr $i + 1)
file_to_trash=${!i}
trash $file_to_trash # trash is a function
;;
-l)
print_trashed_file # print_trashed_file is a function
;;
-b)
i=$(expr $i + 1)
file_to_untrash=${!i}
untrash $file_to_untrash # untrash is a function
;;
-c)
clean_all # clean all is a function
;;
-h)
usage
exit 0
;;
\?)
usage
exit 1
;;
esac
i=$(expr $i + 1)
done
在使用'getopts'时,有两个特殊的变量,它们是 OPTIND 和 OPTARG ,前者表示当前参数在参数列表中的位置——相当于手工解析第二种方法中那个自定义的变量 i ,其值初始时为1, 会在每次取了选项以及其值(如果有的话)后更新; OPTARG 则是在选项需要值时,存储这个选项对应的值。这样,我们这个例子用'getopts'就可以写成:
while getopts d:lb:ch OPT;do
case $OPT in
d)
file_to_trash=$OPTARG
trash $file_to_trash # trash is a function
;;
l)
print_trashed_file # print_trashed_file is a function
;;
b)
file_to_untrash=$OPTARG
untrash $file_to_untrash # untrash is a function
;;
c)
clean_all # clean all is a function
;;
h)
usage
exit 0
;;
\?)
usage
exit 1
;;
esacdone
arg=$(getopt -o d:lb:ch -l delete:,list,back:,clear,help -- $@)
set -- "$arg"
while true
do
case $1 in
-d|--delete)
file_to_trash=$2
trash $file_to_trash # trash is a function
shift 2
;;
-l|--list)
print_trashed_file # print_trashed_file is a function
shift
;;
-b|--back)
file_to_untrash=$2
untrash $file_to_untrash # untrash is a function
shift
;;
-c|--clear)
clean_all # clean all is a function
shift
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
esacdone
function main() {
local OPTIND
while getopts d:lb:ch OPT;do
case $OPT in
d)
file_to_trash=$OPTARG
trash $file_to_trash # trash is a function
;;
l)
print_trashed_file # print_trashed_file is a function
;;
b)
file_to_untrash=$OPTARG
untrash $file_to_untrash # untrash is a function
;;
c)
clean_all # clean all is a function
;;
h)
usage
exit 0
;;
\?)
usage
exit 1
;;
esac
done
}
main $@