1 , the while loop and nested loop
( 1) Grammar format
while-do-done
Repeatedly test the condition of the instruction, and repeat the corresponding command operation as long as the condition is satisfied, until the command is not established or false;
Syntax format:
while test command do command done
( 2) Examples
A , descending output 1-5
[root@test ~]# vi while-1.sh #!/bin/bash i=5 while [ $i -gt 0 ] do echo $i i=$[$i-1] done [root@test ~]# sh while-1.sh 5 4 3 2 1 [root@test ~]#
B. Output the result of adding two numbers
[root@test ~]# cat while-2.sh #!/bin/bash i=1 while [$i -lt 5] do sum=$(($i+$i)) echo "$i+$i=$ sum" ((i++)) done #Double brackets can be used for logical operations, four arithmetic operations [root@test ~]# sh while-2.sh 1+1=2 2+2=4 3+3=6 4+4= 8 [root@test ~]#
( 3) Loop nesting
A. Create user
[root@test ~]# vi name.txt aa bb cc [root@test ~]# vi useradd.sh #!/bin/bash for name in $(cat /root/name.txt) do id $name &>/dev/null if [ $? -ne 0 ];then useradd $name echo "123456" |passwd --stdin $name &>/dev/null echo "$name is created" else echo "$name is exist" fi done [root@test ~]# sh useradd.sh aa is created bb is created cc is created [root@test ~]# id aa uid=501(aa) gid=501(aa) groups=501(aa)
seq is used to generate all integers from one number to another.
Usage: seq [Options]... Mantissa or: seq [Options]... First digit Mantissa or: seq [Option]... First digit Increment Mantissa Print numbers from the first digit to the last digit in a specified increment. -f, --format = printf style format floating point format -s, --separator = partition number strings in the string (default: \ n-) -w, --equal-column width before adding 0 Make the width the same --help display this help message and exit --version display version information and exit
Two ways to loop from 1 to 100 (I haven’t tried other bash shells)
for x in `seq 1 100`;do echo $x;done for x in {1..100};do echo $x;done
-f specifies the output format
#seq -f “%3g” 13 The number of digits is three digits, and no spaces are required
[root@test ~]# seq -f “%3g” 3 “ 1” “ 2” “ 3” [root@test ~]#
#seq -f “%03g” 1 5 The number of digits is three digits, and zeros are missing
[root@test ~]# seq -f “%03g” 1 5 “001” “002” “003” “004” “005” [root@test ~]#
#seq -f "str%03g" 1 3
[root@test ~]# seq -f "str%03g" 1 3 str001 str002 str003 [root@test ~]#
-w specifies the same width as the output number, which is similar to the -f part and cannot be used with the -f option
#seq -w 8 12
[root@test ~]# seq -w 8 12 08 09 10 11 12 [root@test ~]#
-s specifies the separator, the default separator is /n (carriage return)
#seq -s "" 1 5 Space as separator
[root@test ~]# seq -s " " 1 5 1 2 3 4 5 [root@test ~]#
#seq -s "`echo -e "\t"`" 1 3 \t as a separator
[root@test ~]# seq -s "`echo -e "\t"`" 1 3 1 2 3 [root@test ~]#
Note: echo -e interprets escape characters
Personal public number: