在Shell
中提供了三种常用的循环语句:for循环
、while循环
、until循环
,以及一种特殊循环select
(之前我误认为它应该属于判断)。
和c语言一样,可以使用break
,continue
。
for循环
用法一:直接遍历列表
$ cat fordemo.sh
#!/bin/bash
for var in $*
do
echo $var
done
用法二:略写的计数
$ cat fordemo.sh
#!/bin/bash
for var in {1..5}
do
echo $var
done
$ ./fordemo.sh
1
2
3
4
5
注意此处in后面为
{ }
,并且中间为2
个点:..
用法三:跳跃式的略写计数
$ cat fordemo.sh
#!/bin/bash
for var in {1..100..10}
do
echo $var
done
$ ./fordemo.sh
1
11
21
31
41
51
61
71
81
91
用法四:配合seq命令的跳跃式略写计数
$ cat fordemo.sh
#!/bin/bash
for var in $(seq 1 10 100)
do
echo $var
done
$ ./fordemo.sh
1
11
21
31
41
51
61
71
81
91
用法五:无{list},把传参作为默认list
$ cat fordemo.sh
#!/bin/bash
for var
do
echo $var
done
与用法一demo功能相同
用法六:类c风格的计数循环
$ cat fordemo.sh
#!/bin/bash
for ((i=1; i<10; i++))
do
echo $i
done
$ ./fordemo.sh
1
2
3
4
5
6
7
8
9
注意用法六里面for后面为
(( ))
while循环
基本格式:
while [[表达式]]
do
command
command
done
demo:
$ cat fordemo.sh
#!/bin/bash
i=0
while [[ $i -lt 8 ]]
#或者while (( $i -lt 8 )),while (( $i < 8 ))
do
let "i++"
echo $i
done
$ ./fordemo.sh
1
2
3
4
5
6
7
8
while后面使用
[[ ]]
时,既可以使用测试比较运算符
,又可以使用普通的运算符
;但是while后面使用(( ))
时,只可以使用普通的运算符
。
unitl循环
基本格式:
until 表达式
do
command
command
done
用法与while大同小异
select结构用于判断
select功能与case类似,于用户交互性更强
- 基本结构:
select var in {list}
do
command
...
break
done
或者
select var
do
command
...
break
done
这种方式通过命令行来传递select参数列表
demo:
$ cat selectdomo.sh
#!/bin/bash
echo "What is your favorite clolor?"
select color in "red" "blue" "green" "white" "blank"
do
break
done
echo "You have selected $color"
$ ./selectdomo.sh
What is your favorite clolor?
1) red
2) blue
3) green
4) white
5) blank
#? 5 #5为我手动输入
You have selected blank
$ cat selectdomo.sh
#!/bin/bash
echo "What is your favorite clolor?"
select color
do
break
done
echo "You have selected $color"
./selectdomo.sh red blank
What is your favorite clolor?
1) red
2) blank
#? 2
You have selected blank
$ cat selectdemo.sh
#!/bin/bash
export PS3="Please,input:"
list=(first two three four five)
select choice in ${list[*]}
do
echo -n "Your choice is $choice."
echo " Copy That!"
break
done