1. for循环格式
带列表的for循环
for var in {1..10}
# for var in {1,2,3,4,5,6,7,8,9,10}
do
command
...
done
for var in {1..50..2}
#for var in {1,3,5,7,9..,49}
do
command
...
done
类C的for循环
for((integer = 1; integer <= 5; integer++))
do
command
...
done
无列表的for循环
for argument
do
command
...
done
2. while循环格式
while expression
do
command
command
```
done
#!/bin/bash
#计数器控制的while循环
sum=0
i=1
while(( i <= 100 ))
do
let "sum+=i"
let "i += 2"
done
echo "sum=$sum"
#!/bin/bash
#结束标记控制的while循环
echo "Please input the num(1-10) "
read num
while [[ "$num" != 4 ]]
do
if [ "$num" -lt 4 ]
then
echo "Too small. Try again!"
read num
elif [ "$num" -gt 4 ]
then
echo "To high. Try again"
read num
else
exit 0
fi
done
echo "Congratulation, you are right! "
#!/bin/bash
#标志控制的while循环
echo "Please input the num "
read num
sum=0
i=1
signal=0
while [[ "$signal" -ne 1 ]]
do
if [ "$i" -eq "$num" ]
then
let "signal=1"
let "sum+=i"
echo "1+2+...+$num=$sum"
else
let "sum=sum+i"
let "i++"
fi
done
#!/bin/bash
#命令行控制的while循环
echo "number of arguments is $#"
echo "What you input is: "
while [[ "$*" != "" ]]
do
echo "$1"
shift
done