【转】Linux Shell 中 for 循环的几种常用写法

1 、数字性循环:

( 1 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for((i=1;i<=10;i++))
do
echo $(expr $i \* 3 + 1)
done

[root@host ~]# 
[root@host ~]# sh test.sh 
4
7
10
13
16
19
22
25
28
31
[root@host ~]#

( 2 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for i in $(seq 1 10)
do 
echo $(expr $i \* 3 + 1)
done

[root@host ~]# 
[root@host ~]# sh test.sh 
4
7
10
13
16
19
22
25
28
31
[root@host ~]#

( 3 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for i in {1..10}
do
echo $(expr $i \* 3 + 1)
done

[root@host ~]# 
[root@host ~]# sh test.sh 
4
7
10
13
16
19
22
25
28
31
[root@host ~]#

( 4 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
awk 'BEGIN{for(i=1; i<=10; i++) print i}'

[root@host ~]# 
[root@host ~]# sh test.sh 
1
2
3
4
5
6
7
8
9
10
[root@host ~]#

2 、字符性循环

( 1 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for i in `ls`
do 
echo $i is file name\!
done

[root@host ~]# 
[root@host ~]# sh test.sh 
test.sh is file name!
works is file name!
[root@host ~]#

( 2 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for i in $*
do
echo $i is input chart\!
done

[root@host ~]# 
[root@host ~]# sh test.sh abc 123
abc is input chart!
123 is input chart!
[root@host ~]#

( 3 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for i in f1 f2 f3
do
echo $i is appoint
done

[root@host ~]# 
[root@host ~]# sh test.sh 
f1 is appoint
f2 is appoint
f3 is appoint
[root@host ~]#

( 4 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
list="rootfs usr data data2"
for i in $list
do
echo $i is appoint
done

[root@host ~]# 
[root@host ~]# sh test.sh 
rootfs is appoint
usr is appoint
data is appoint
data2 is appoint
[root@host ~]#

3 、路径查找

( 1 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for file in /proc/*
do
echo $file is file path \!
done

[root@host ~]# 
[root@host ~]# sh test.sh 
/proc/1 is file path !
/proc/100 is file path !
/proc/10140 is file path !
/proc/1018 is file path !
/proc/1019 is file path !
......
[root@host ~]#

( 2 )

[root@host ~]# cat test.sh 
#!/bin/bash
 
for file in $(ls *.sh)
do
echo $file is file path \!
done

[root@host ~]# 
[root@host ~]# sh test.sh 
test.sh is file path !
[root@host ~]#

 

参考自:

  • https://blog.csdn.net/babyfish13/article/details/52981110

这篇文章对你有帮助吗?

相关文章

发表评论?

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据