Format
For name in list
Do
Loop body
Done
Example:
List the usernames, uid, and shell in the/etc/passwd file, Row 1, 3, 6, and 12
#!/bin/bashfor line in 1 3 6 12do Username=$(head -$line /etc/passwd | tail -1 | awk -F: ‘{print $1}‘) Userid=$(head -$line /etc/passwd | tail -1 | awk -F: ‘{print $3}‘) Usershell=$(head -$line /etc/passwd | tail -1 | awk -F: ‘{print $7}‘) echo -e "UserName:$Username\tUserID:$Userid\tUserShell:$Usershell"done
List generation
1. Give/etc/fstab/etc/inittab one by one
2. wildcard matching, for example,/var /*
3. Command production list
Example:
#!/bin/bashfor File in `ls /var`do file /var/$Filedone
4. The number sequence {1 .. 100} is automatically expanded to 1 to 100.
{Start number... end number}
SEQ automatically generates a numerical sequence:
Sed 3: generated from 1 to 3
Sed 3 16 production from 3 to 16
Sed 3 2 16 generates 3 to 16, but the interval is 2
3 5 7 9 11 13 15
Exercise: display the usernames and shells of all/etc/passwd users.
#!/bin/bashLINES=$(wc -l /etc/passwd | awk -F" " ‘{print $1}‘)for I in $(seq 1 $LINES)do head -$I /etc/passwd | tail -1 | awk -F: ‘{print $1,$7}‘done
Arithmetic Operations in shell scripts
Shell does not support floating point numbers: In the calculation result, the floating point will be an integer.
1.22 = 1; 1.99 = 1
Arithmetic Operation Implementation Method
$ [Expression]
For example
A = 1
B = 2
C = $ [$ A + $ B]
Echo $ C
3
Script contact
Calculate the sum of 0 to 100
#!/bin/bashsum=0for i in $(seq 0 100)do sum=$[$sum+$i]doneecho $sum
Calculate the total uid of all users
#!/bin/bashidsum=0for i in $(awk -F: ‘{print $3}‘ /etc/passwd)do idsum=$[$idsum+$i]doneecho $idsum
This article from the "hanging sword" blog, please be sure to keep this source http://sublime.blog.51cto.com/8856101/1440022
Shell script basics ----- For Loop