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:
- Open the terminal and use the following command to create a new shell script file, for example, name it sum.sh:
nano sum.sh
- 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"
- 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
- 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.