1. Control flow statement for
( 1) For statement format
for variable in parameter list do command done
or
for variable in parameter list; do command done
Note: Each time you only take the data of one loop list, give it to the following code block.
( 2) Examples of for statements
A , direct value
[root@test ~]# vi for-1.sh #!/bin/bash for i in a b c d e do echo test is $i done [root@test ~]# sh for-1.sh test is a test is b test is c test is d test is e [root@test ~]#
B. Value in variable
[root@test ~]# vi for-2.sh #!/bin/bash list="a b c d e" for i in $list do echo test is $i done [root@test ~]# sh for-2.sh test is a test is b test is c test is d test is e [root@test ~]#
C , take the value from the command
[root@youxi1 ~]# vim d.sh #!/bin/bash for i in `head -5 /etc/passwd` do echo $i done [root@test ~]# sh for-3.sh root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin [root@test ~]#
( 3) Custom shell separator
By default, the base shell will use spaces, tabs, and newlines as delimiters. Customized as separator through IFS .
Specify a single character as the separator:
IFS=: #Use: colon as separator
IFS can specify a single character as a separator, IFS=: (using a colon as a separator); IFS can also specify multiple characters as a separator, IFS=\n:; (using a backslash, n, colon, semicolon as Separator). Note: In IFS, $'\n' and $'\t' are line breaks and tabs.
A. Example 1
[root@test ~]# vim a.sh #!/bin/bash list="a1 a2 b1 b2 \"hello world\"" for i in $list do echo $i done [root@test ~]# sh a.sh a1 a2 b1 b2 "hello world"
B. Specify \n carriage return as the separator of the for statement
[root@test ~]# vi for-4.sh #!/bin/bash IFS=$'\n' for i in `head -2 /etc/passwd` do echo "$i" done [root@test ~]# sh for-4.sh root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin [root@test ~]#
( 4) For statement in C language
A. Grammar format
for ((i=0;i<10;i++)) do commands done
B. Single variable loop
[root@test ~]# vi for-5.sh #!/bin/bash for (( i=1 ; i<=3 ; i++ )) do echo num is $i done [root@test ~]# sh for-5.sh num is 1 num is 2 num is 3 [root@test ~]#
C , for nesting (multivariate)
[root@test ~]# vi for-6.sh #!/bin/bash for ((a=1,b=5 ; a<6 ; a++,b--)) do echo num is $a - $b done [root@test ~]# sh for-6.sh num is 1 - 9 num is 2 - 8 num is 3 - 7 num is 4 - 6 num is 5 - 5 [root@test ~]#
D , print triangle
[root@test ~]# vi for-7.sh #!/bin/bash for ((i=1;i<5;i++));do for ((j=1;j<=i;j++));do echo -n '*' done echo -e "\n" done [root@test ~]# sh for-7.sh * ** *** **** [root@test ~]#
-e Interpret escape characters \t tab \n press enter \b delete the previous character \a sound an alarm \033[32m$var\033[0m 32---green 31---red -n no line feed
Personal public number: