四.Shell之循环用法
2019-02-03 本文已影响3人
Dakini_Wind
在Shell中提供了三种常用的循环语句:for循环、while循环、until循环。
和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大同小异