First, the Loop statement for
loop control statements in Bash :for,while,until
For loop Syntax 1:
For variable name in list;
Loop body
Done
Operating features:
First pass: Assigns the first element in the list the variable name definition, then executes the completion loop body;
Second time: 、、、 until the end of the element traversal, the loop exits
How the list is generated:
1, directly listed as: stu100 stu101 stu102 or {stu100,stu101,stu102}
2. Generate a list of integers such as: {start_num. End_num} Example: {1.. 10} specific format, representing 1 to 10
3, using the file name wildcard mechanism to generate a list
4. Using Command generation
Seq Last
Seq First Last
Seq First STEP Last
Cases:
[[email protected] ~]# SEQ 1 2 1013579[[email protected] ~]#
2, create 10 users user10-user19, password with the user name, in/tmp/create 10 empty files File10-file19, the FILE10-FILE19 belong to the main group to USER10-USER19
[email protected] script]# cat 5useradd.sh #/bin/bashfor i in {10..19} douseradd user$itouch/tmp/file$ichown User$i:user $i/tmp/file$idone[[email protected] script]#
3. Write a script to display the content type of each file in the/var/log directory using the file command.
[email protected] shell]# cat 3.sh#!/bin/bashfor i in/var/log/*dofile $i done
6, display the user name and ID number of 3rd, 7 and 11 users in/etc/passwd
[[email protected] shell]# cat 6.sh#!/bin/bashfor i in {3,7,11}dohead-$i/etc/passwd|tail-1|cut-d:-f1,3done[[email Pro Tected] shell]# Bash 6.shdaemon:2shutdown:6operator:11
7. Display the user name of the user in the/etc/passwd file in the even row
[[email protected] script]# cat 4useradd.sh #/bin/bashlines=$ (cat/etc/passwd|wc-l) for I in $ (Seq 2 2 $lines) dohead-n $i /etc/passwd|tail-1|cut-d:-f1done[[email protected] script]# bash 4useradd.shbinadmsynchaltuucpgamesftpdbusrpcrpcuserhaldaemonsaslauthsshdoprofilexjstu101stu105stu107stu111stu120stu122stu 131usersbusersibuserx111userj333x111[[email protected] script]# bash 4useradd.sh|wc-l26[[email protected] script]#
Practice:
1. Calculate the sum of all positive integers within 100 :
[[email protected] shell]# cat 8.sh#!/bin/bashsum=ofor i in {1..100}do sum=$[$sum + $i]done echo $sum [[email protected] sh ell]# Bash 8.sh5050
2. Calculates the sum of the sum and odd numbers of all even numbers within 1000, respectively
[[email protected] shell]# bash 9.shThe sum is 2500The sum is 2550[[email protected] shell]# cat 9.sh#!/bin/bashy=0for i I N $ (Seq 1 2) do y=$[$y + $i]doneecho ' The sum is $y ' ################ #for A in $ (Seq 2 2) do b=$[$b + $a]doneecho "the Sum is $b "
Shell Foundation three: Loop statement for