[iyunv@sh shell]# cat for1.sh
#!/bin/bash
for test in aaa bbb ccc ddd
do
echo the next state is $test
done
[iyunv@sh shell]# sh for1.sh
the next state is aaa
the next state is bbb
the next state is ccc
the next state is ddd
$test变量的值会在shell脚本的最后一次迭代中一直保持有效,除非你修改了它
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[iyunv@sh shell]# cat for1.sh
#!/bin/bash
for test in aaa bbb ccc ddd
do
echo the next state is $test
done
echo "the last state we visited was $test"
test=fff
echo "wait. now we're visiting $test"
[iyunv@sh shell]# sh for1.sh
the next state is aaa
the next state is bbb
the next state is ccc
the next state is ddd
the last state we visited was ddd
wait. now we're visiting fff
list="aaa bbb ccc ddd eee"
list=$list" Connecticut"
for state in $list
do
echo "Have you ever visited $state"
done
[iyunv@sh shell]# sh for3.sh
Have you ever visited aaa
Have you ever visited bbb
Have you ever visited ccc
Have you ever visited ddd
Have you ever visited eee
Have you ever visited Connecticut
[iyunv@sh shell]# cat for6.sh
#!/bin/bash
for file in /home/*
do
if [ -d "$file" ];then
echo "$file is a directory"
elif [ -f "$file" ];then
echo "$file is a file"
fi
done
[iyunv@sh shell]# sh for6.sh
/home/apache-tomcat-8.0.28.tar.gz is a file
/home/dir1 is a directory
/home/dir2 is a directory
/home/fie1 is a file
/home/fie2 is a file
/home/fie22 is a file
[iyunv@sh shell]# cat for7.sh
#!/bin/bash
for file in /home/* /home/badtest
do
if [ -d "$file" ];then
echo "$file is a directory"
elif [ -f "$file" ];then
echo "$file is a file"
else
echo "$file doesn't exist"
fi
done
[iyunv@sh shell]# sh for7.sh
/home/apache-tomcat-8.0.28.tar.gz is a file
/home/dir1 is a directory
/home/dir2 is a directory
/home/fie1 is a file
/home/fie2 is a file
/home/fie22 is a file
/home/badtest doesn't exist
二、C语言风格的for命令 2.1 C语言风格的for命令
C语言的for命令有一个用来指明变量的特殊方法、一个必须保持成立才能继续迭代的条件,以及另一个为每个迭代改变变量的方法。当指定的条件不成立时,for循环就会停止。条件等式通过标准的数字符号定义。
for (i=0; i<10; i++)
bash中C语言风格的for循环的基本格式:
for (( variable assignment;condition;iteration process))
for (( a = 1; a < 10; a++ ))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[iyunv@sh shell]# cat c1.sh
#!/bin/bash
for (( i=1; i < 10; i++ ))
do
echo "The next number is $i"
done
[iyunv@sh shell]# sh c1.sh
The next number is 1
The next number is 2
The next number is 3
The next number is 4
The next number is 5
The next number is 6
The next number is 7
The next number is 8
The next number is 9
while echo $var1
[ $var1 -ge 0 ]
do
echo "This is inside the loop"
var1=$[ $var1 - 1 ]
done
[iyunv@sh shell]# sh w2.sh
10
This is inside the loop
9
This is inside the loop
8
This is inside the loop
7
This is inside the loop
6
This is inside the loop
5
This is inside the loop
4
This is inside the loop
3
This is inside the loop
2
This is inside the loop
1
This is inside the loop
0
This is inside the loop
-1