我有一个脚本:
#!/bin/sh
function usage() {
cat << EOF >&2
Usage: $0 [-h] [-rs <start_num>] [-re <end_num>]
-h: help: displays list of options for command $0
-rs<int>: range start: should be the number to go from - the lower of the two ranges. <int>
-re<int>: range end: should be the number to add up to - the highest of the two ranges. <int>
EOF
exit 1
}
function addition() {
sum=0
for number in "$@"; do
sum=$(( sum + number))
done
# set defaults
rangeStart=0
rangeEnd=0
error=false
# loop arguments
OPTIND=1
while getopts rs:re:h: o; do
case $o in
rs) rangeStart=$OPTARG;;
re) rangeEnd=$OPTARG;;
h) usage;;
*) error=true;;
esac
done
shift $((OPTIND - 1))
echo $rangeStart
echo $rangeEnd
if [ "$error" = true ] ; then
echo 'Invalid argument passed. See addition -h for usage.'
else
echo 'Total: '$sum
fi
}
目前,我只是尝试添加命令参数,以便用户可以键入:
$ addition -rs 4 -re 10
它从 4 循环到 10(因此添加4 + 5 + 6 + 7 + 8 + 9 + 10
)并输出总数。
但执行上述操作会返回以下输出:
0
0
传递的参数无效。请参阅附加 -h 了解用法。
所以它不认识我的参数。当我将命令更改为:
$ addition -rs4 -re10
它输出相同的..我在脚本中做错了什么?