Syntax: for variable name in condition; do ...; done
Case 1: Calculate the sum of all numbers from 1 to 100
#!/bin/bash
sum=0
for i in `seq 1 100`
do
sum=$[$sum+$i]
echo $i
done
echo $sum
Analyzing the above case, let's first look at the following shell
#!/bin/bash
for i in `seq 1 10`
do
echo $i
done
Execute this shell, the result is as follows, the result is that the value from 1 to 10 is returned
[root@lijie-01 ~]# sh for1.sh
1
2
3
4
5
6
7
8
9
10
In fact, in linux, we use more loops on files Case 2: file list loop
#!/bin/bash
cd /etc/
for a in `ls /etc/`
do
if [ -d $a ]
then
ls -d $a
fi
done
There is one situation to pay attention to. Space or carriage return is used as the separator in the for loop. When using the for i in ls ./
;do echo $i;done command ls ./
as the judgment condition, when there is a space in the file name, a file will be Space split to split into multiple files
[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
Above, so we need to pay attention to the space or the Enter key when using this type of judgment condition in the for i in ls ./
;do echo $i;done command in the futurels ./