shell-scripts/tutorials/basic/16-nums-total.sh

17 lines
418 B
Bash
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
#Program:
# 输入一个值计算从0到这个值的所有和比如输入100那么输出5050
num=0
sum=0
if [ -n "$1" ] && echo "$1" | grep -Eq "^[-+]?[0-9]+$" && [ "$1" -ge 0 ];then
while [ "$num" -le "$1" ]
do
sum=$(($num+$sum))
num=$((num+1))
done
echo "1-${1}求和的结果为:${sum}"
else
echo "输入的数值不正确必须为非空且大与等于0的整数"
fi