getopts 的设计目标是在循环中运行,每次执行循环,getopts 就检查下一个命令行参数,并判断它是否合法。即检查参数是否以 - 开头,后面跟一个包含在 options 中的字母。如果是,就把匹配的选项字母存在指定的变量 variable 中,并返回退出状态0;如果 - 后面的字母没有包含在 options 中,就在 variable 中存入一个 ?,并返回退出状态0;如果命令行中已经没有参数,或者下一个参数不以 - 开头,就返回不为0的退出状态。
二、使用举例
vi test.sh
#!/bin/bash while getopts h:ms option do case "$option" in h) echo "option:h, value $OPTARG" echo "next arg index:$OPTIND";; m) echo "option:m" echo "next arg index:$OPTIND";; s) echo "option:s" echo "next arg index:$OPTIND";; \?) echo "Usage: args [-h n] [-m] [-s]" echo "-h means hours" echo "-m means minutes" echo "-s means seconds" exit 1;; esac done echo "*** do something now ***"
chmod +x test.sh
./ test.sh -h 100 -ms #运行结果option:h, value 100 next arg index:3 option:m next arg index:3 option:s next arg index:4 *** do something now ***./ test.sh -t
./args: illegal option -- t Usage: args [-h n] [-m] [-s] -h means hours -m means minutes -s means seconds注: