[CentOS 7Shell programming 5], for loop #180211

hellopasswd


for loop

  • Syntax: for variable name in condition; do...; done
  • 案例1 #!/bin/bash sum=0 for i in seq 1 100 do sum=$[$sum+$i] echo $i done echo $sum
[root@localhost ~]# cd shell/
[root@localhost shell]# vi 1.sh
      1 #!/bin/bash
      2 for i in `seq 1 10`
      3 do
      4     echo $i
      5 done
[root@localhost shell]# sh 1.sh 
1
2
3
4
5
6
7
8
9
10

[root@localhost shell]# vi 1.sh
      1 #!/bin/bash
      2 sum=0
      3 for i in `seq 1 100`
      4 do  
      5     sum=$[$sum+$i]
      6 done
      7     echo $sum
[root@localhost shell]# sh 1.sh 
5050

If you want to know the calculation process of the for statement, you can add a parameter -x

[root@localhost shell]# vi 1.sh
      1 #!/bin/bash
      2 cd /etc/
      3 for a in `ls /etc/`
      4 do
      5     if [ -d $a ]
      6     then
      7         ls -d $a
      8     fi
      9 done

traverse

[root@localhost shell]# for i in `seq 1 3`; do echo $i; done
1
2
3
[root@localhost shell]# seq 1 3
1
2
3
[root@localhost shell]# for i in 1 2 3; do echo $i; done
1
2
3

Notice

[root@localhost shell]# mkdir user
[root@localhost shell]# cd user/
[root@localhost user]# touch 1 2
[root@localhost user]# touch 3\ 4
[root@localhost user]# ls -l
total 0
-rw-r--r--. 1 root root 0 Feb 10 21:04 1
-rw-r--r--. 1 root root 0 Feb 10 21:04 2
-rw-r--r--. 1 root root 0 Feb 10 21:04 3 4
[root@localhost user]# for i in `ls ./`; do echo $i; done
1
2
3
4

In this form, the for loop will use spaces, carriage returns, and tabs as a delimiter


Modified on 180211

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325121662&siteId=291194637