基于Shell中for循环的几个常用写法

第一类:数字性循环

#法一:
[root@VPC3-CS-TEST sbin]# for i in `seq 1 3`;do echo "$i";done
1
2
3
#法二:
[root@VPC3-CS-TEST sbin]# for i in $(seq 1 3);do echo "$i";done
1
2
3
#法三:
[root@VPC3-CS-TEST sbin]# for i in {1..3};do echo "$i";done
1
2
3

第二类:字符性循环

#法一:
[root@VPC3-CS-TEST sbin]# for i in f1 f2 f3;do echo $i is appoint;done
f1 is appoint
f2 is appoint
f3 is appoint
#法二:
[root@VPC3-CS-TEST sbin]# cat for.sh
#!/bin/bash

list="rootfs usr data data2"
for i in $list;
do
  echo $i is appoint;
done
[root@VPC3-CS-TEST sbin]# sh for.sh
sh for.sh
rootfs is appoint
usr is appoint
data is appoint
data2 is appoint

第三类:路径查找

#法一:
[root@VPC3-CS-TEST sbin]# for i in /tmp/*; do echo $i is file path \!; done
/tmp/Aegis-<Guid(5A2C30A2-A87D-490A-9281-6765EDAD7CBA)> is file path !
/tmp/cpu_stat is file path !
/tmp/disk_io is file path !
/tmp/mysql.sock is file path !
/tmp/netio_stat is file path !
#法二:
[root@VPC3-CS-TEST sbin]# for i in "$(ls /tmp/cpu*)";do echo "$i" is file path \!;done
/tmp/cpu_stat is file path !
04-10 00:12