Use of for loop in shell
The common for loop usage mainly includes the following:
Grammatical structures:
for item in (list)
do
command
done
例:
#!/bin/bash
for i in “土豆” “菠菜” “鱿鱼”
do
echo “我喜欢吃$i 。”
done
Output result:
"I like to eat "potatoes"."
"I like to eat "spinach"."
"I like to eat "squid"."
Example to calculate the sum from 1 to 500
Method 1:
#!/bin/bash
sum=0
for item in {1..500}
do
let "sum+=item"
done
echo "总数为:${sum}"
Way 2:
#!/bin/bash
sum=0
for item in $(seq 1 500)
do
let "sum+=item"
done
echo "总数为:${sum}"
Output result: 120250
3. For loop in C-like language
Grammatical structures:
for ((exp1;exp2;exp3;))
do
command
done
Example:
#!/bin/bash
for ((num=1;num<=100;num++))
do
echo -n "$num "
done
Calculate the sum of 1 to 100 and the odd sum of 1 to 100
#!/bin/bash
sum1=0
sum2=0
for((i=1,j=1;i<=100;i++,j+=2))
do
let "sum1+=i"
if [ $j -lt 100 ];then
let "sum2+=j"
fi
done
echo "sum1=$sum1"
echo "sum2=$sum2"
Output:
sum1=5050
sum2=2500