Linux While Loop Sum Script: 1-100

You can use a while loop to calculate the sum of numbers from 1 to 100 by following these steps:

  1. Open the terminal and use the following command to create a new shell script file, for example, name it sum.sh:
nano sum.sh
  1. Enter the following code in the sum.sh file:
#!/bin/bash

sum=0
i=1

while [ $i -le 100 ]
do
  sum=$((sum + i))
  i=$((i + 1))
done

echo "1到100的和为:$sum"
  1. Save and exit the file, then in the terminal, enter the following command to add execute permission to the sum.sh file:
chmod +x sum.sh
  1. Finally, run the sum.sh file to find the sum of numbers from 1 to 100.
./sum.sh

After running, the terminal will display the sum of numbers 1 to 100.

bannerAds