100個Shell腳本——【腳本5】數字求和


【腳本5】數字求和
編寫shell腳本,要求輸入一個數字,然后計算出從1到輸入數字的和,要求,如果輸入的數字小於1,則重新輸入,直到輸入正確的數字為止,示例:

一、腳本

#!/bin/bash
while :
do
   read -p "Please enter a positive integer: " n
   if [ $n -lt 1 ]
   then
      echo "It can't be less than 1"
   else
      break
   fi
done

num=1
for i in `seq 2 $n`
do
   num=$[$num+$i]
done

echo $num

二、小結:
1、for 循環
[1]LInux shell之(for in 用法總結) https://blog.csdn.net/wzj_110/article/details/86669426
[2]Shell腳本中使用變量作為for循環范圍 https://www.jdoodle.com/test-bash-shell-script-online/
2、Shell變量與算術運算
[1]Shell變量與算術運算 https://www.cnblogs.com/yweihum/p/9497593.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM