语法:for 变量名 in 条件; do …; done
案例1:计算1到100全部数字的和linux
#!/bin/bash sum=0 for i in `seq 1 100` do sum=$[$sum+$i] echo $i done echo $sum
分析上面的案例,咱们先看下下面shellshell
#!/bin/bash for i in `seq 1 10` do echo $i done
执行这个shell,结果以下,结果是返回了1到10的值vim
[root@lijie-01 ~]# sh for1.sh 1 2 3 4 5 6 7 8 9 10
其实在linux中咱们用的更多的是对文件作循环 案例2:文件列表循环bash
#!/bin/bash cd /etc/ for a in `ls /etc/` do if [ -d $a ] then ls -d $a fi done
有下面一个状况须要注意,for循环时以空格或者回车做为分割符,在使用 for i in ls ./
;do echo $i;done命令里面ls ./
做为判断条件时,当文件名中有空格时,一个文件会以空格分割拆分红多个文件code
[root@lijie-01 shell]# vim for2.sh [root@lijie-01 shell]# touch 1 2 [root@lijie-01 shell]# touch 3\ 4.txt [root@lijie-01 shell]# ll 总用量 44 -rw-r--r-- 1 root root 0 4月 20 06:24 1 -rw-r--r-- 1 root root 0 4月 20 06:24 2 -rw-r--r-- 1 root root 0 4月 20 06:24 3 4.txt [root@lijie-01 shell]# ls 3 ls: 没法访问3: 没有那个文件或目录 [root@lijie-01 shell]# for i in `ls ./`;do echo $i;done //这里循环出来3 4.txt这个文件被拆分为两个文件了 1 2 3 4.txt
以上,所以咱们之后在使用 for i in ls ./
;do echo $i;done命令里面ls ./
这种类型的判断条件时,须要注意空格或者回车键for循环