Thinking deeply about for, while, until loops, break and continue statements, echo escape characters, you are one step closer to senior IT people!

One, for loop statement

(1), for statement structure

Read different variable values ​​to execute the same group of commands one by one

语句结构:
for 变量名 in 取值列表
do
	命令序列
done
语句结构举例:
for 收件人 in 邮件地址列表
do
	发送邮件
done

Insert picture description here

(2) Examples of for loops:

Add the function of the seq command

[root@gcc?~]#seq 1 10    #从1到10将内容列出来
1
2
3
4
5
6
7
8
9
10
[root@gcc?~]#seq 1 2 10    #范围是1到10,从1开始,每次加2
1
3
5
7
9
方法1:
[root@gcc ~]#vim xunhuan.sh
#!/bin/bash
for i in {1..10}        #i从1到10遍历一遍
do                      #执行循环
  echo "---------"      #自己加的分割线,方便阅读
  echo $i               #输出每次遍历的i的值
  echo $[ $i + 1 ]      #输出遍历的i每次的值加上1之后的值,此处使用[]是因为需要调用$i + 1这个变量
done                    #结束循环

[root@gcc ~]#sh xunhuan.sh       #执行脚本
---------            #输出的分割线,没什么主要重要,就是为了看的时候更清晰点
1                    #这个数字是$i输出的从1到10每次遍历的值
2                    #这个数字是$i + 1 输出的值,表示每次$i变量的结果再加上一个1
---------
2
3
---------
3
4
---------
4
5
---------
5
6
---------
6
7
---------
7
8
---------
8
9
---------
9
10
---------
10
11

方法2:
[root@gcc ~]#vim xunhuan.sh
#!/bin/bash
for i in $(seq 1 2 10)        #表示i范围是1到10之间,从1开始,每次得出的结果加上2
do 
  echo "---------"
  echo $i
  echo $[ $i + 1 ]            #表示$i的结果加上1后输出
done   

[root@gcc ~]#sh xunhuan.sh 
---------
1
2
---------
3
4
---------
5
6
---------
7
8
---------
9
10

方法3:
[root@gcc ~]#vim xunhuan.sh
 #!/bin/bash
for ((i=1;i<=10;i++))         #也是从1开始一直到10,每次加1,和上面两种方法一样,只是表达方式不同
do 
  echo "---------"
  echo $i
  echo $[ $i + 3 ]
done

[root@gcc ~]#sh xunhuan.sh 
---------
1
4
---------
2
5
---------
3
6
---------
4
7
---------
5
8
---------
6
9
---------
7
10
---------
8
11
---------
9
12
---------
10
13
 

Similarly, we can also take values ​​in the file:

[root@gcc ~]#cat 123.txt     #这是一个具有内容的文件,注意IFS字段分隔符默认包括空格符,制表符和换行符
1
2
3
4
5
6
7
8
9

[root@gcc ~]#vim xunhuan.sh
#!/bin/bash
a=`cat $HOME/123.txt`     或  $( cat $HOME/123.txt )        #使用HOME环境变量,调用123.txt文件中的内容,将该变量赋值给a。也直接可以跟上文件的绝对路径,可以不加环境变量。
for i in $a                    #从a变量中进行遍历
do
  echo "---------"
  echo $i
  echo $[ $i + 3 ]
done

[root@gcc ~]#sh xunhuan.sh         #同样也可以输出结果
---------
1
4
---------
2
5
---------
3
6
---------
4
7
---------
5
8
---------
6
9
---------
7
10
---------
8
11
---------
9
12

Example 1: Calculate the sum of all integers from 1 to 100.

[root@gcc?~]#vim test1.sh
#!/bin/bash              #固定格式
#this is zhengshuhe      #对于该脚本的注释,可不加
sum=0                    #对于整数和的运算来说,整数和sum也算是一个变量,所以在运算之前我们需要先定义整数和起始的一个数字,这里起始的数字是0,因为1-100的和是从0开始算起的。
for i in {1..100}        #遍历需要运算的数字区间,即0-100
do                       #开始执行以下命令块
  sum=$[$i+$sum]         #这里是求和的运算。我们可以理解为:这次遍历出来的数字,加上上一次运算出来的整数的和即为这次算出来的整数和。比如这次循环遍历到了3,上次的和是1+2=3,所以这次就等于上次的和1+2=3加上这次遍历的数字3,就得出这次循环算出来的整数和为6.
done                     #结束for循环
echo $sum                #输出结果

[root@gcc ~]#chmod +x test1.sh      #赋权给脚本文件
[root@gcc ~]#./test1.sh             #执行脚本文件
5050                                #得出1-100的所有的整数和为5050

Example 2: Add users in batch

[root@gcc ~]#touch user.txt     #首先创建一个包含所有需要创建账号的用户名
[root@gcc ~]#vim user.txt 
wangyi             #注意一个姓名之间不要有空格
wanger
wangsan
wangsi


[root@gcc ~]#vim test2.sh      #编辑脚本
#!/bin/bash
#pi liang tianjia yonghu
a=$(cat /root/user.txt)        #定义变量a,使a遍历user.txt,注意遍历的文件要使用绝对路径
for i in $a                    #定义变量i,使i使用$a中的内容
do
   useradd $i                  #添加用户,用户名从变量i中获取
   echo "123123" | passwd --stdin $i     #给用户添加密码,密码从$i中获取
   echo "$i添加成功!"
done

(优化脚本:echo "123123" | passwd --stdin $i &> /dev/null)

[root@gcc ~]#sh test2.sh 
更改用户 wangyi 的密码 。
passwd:所有的身份验证令牌已经成功更新。
wangyi添加成功!
更改用户 wanger 的密码 。
passwd:所有的身份验证令牌已经成功更新。
wanger添加成功!
更改用户 wangsan 的密码 。
passwd:所有的身份验证令牌已经成功更新。
wangsan添加成功!
更改用户 wangsi 的密码 。
passwd:所有的身份验证令牌已经成功更新。
wangsi添加成功!

Example 3: Check host status in batches according to IP address

[root@gcc ~]#touch ipadds.txt
[root@gcc ~]#vim ipadds.txt 
[root@gcc ~]#vim ipadds.txt      #在文本中添加需要检查的主机的IP地址
192.168.200.1
192.168.200.2
192.168.200.3
192.168.200.4
192.168.200.5

[root@gcc ~]#vim test3.sh       #编写脚本
#!/bin/bash
a=`cat /root/ipadds.txt`        #遍历ipadds.txt文件
for i in $a                     #定义变量i从$a中取值
do
   ping -c 3 -i 0.2 -W 3 $i &> /dev/null     #开始ping检测,-c是ping的次数,-i是每次ping的时间,-w是ping的时候延时时间
   if [ $? -eq 0 ]              #判断语句,当使用$?返回0时,说明上面ping成功
   then
   echo "$i开启!"
   else
   echo "$i关闭!"
   fi
done

[root@gcc ~]#sh test3.sh      #执行脚本
192.168.200.1开启!
192.168.200.2开启!
192.168.200.3关闭!
192.168.200.4关闭!
192.168.200.5关闭!

Two, while loop statement

While statement structure
Test a certain condition repeatedly, and execute repeatedly as long as the condition is satisfied.

语句结构:
while 条件测试操作
do
	命令序列
done
语句结构示例:
while 未猜中正确的价格
do
	反复猜测商品价格
done

Insert picture description here
Example 1: Use whie statement to list numbers from 1 to 10

[root@gcc ~]#vim test4.sh
#!/bin/bash
a=0                    #定义开始数字为0
while [ $a -le 10 ]    #使用while语句,当a小于等于10时一直执行while循环
do
  echo $a              #输出$a的值
  a=$[$a+1]            #a每次加1进行循环,直到等于10时结束循环
done

或者表示为

[root@gcc ~]#vim test4.sh
#!/bin/bash
a=0
while [ $a -le 10 ]
do
  echo $a
  let a+=1 (或 let a++)     #使用let命令进行运算,使a每次加1
done


[root@gcc ~]#sh test4.sh 
0
1
2
3
4
5
6
7
8
9
10

Example 2: Add users in batch

[root@gcc ~]#vim test5.sh
#!/bin/bash
i=1                      #用户从1开始
while [ $i -le 20 ]      #当小于等于20时一直执行while循环,直到20停止循环
do    
  useradd stu$i
  echo "123123" | passwd --stdin stu$i &> /dev/null
  echo "stu$i添加成功!"
  let i+=1            #用户每次+1进行添加
done

[root@gcc ~]#sh test5.sh 
stu1添加成功!
stu2添加成功!
stu3添加成功!
stu4添加成功!
stu5添加成功!
stu6添加成功!
stu7添加成功!
stu8添加成功!
stu9添加成功!
stu10添加成功!
stu11添加成功!
stu12添加成功!
stu13添加成功!
stu14添加成功!
stu15添加成功!
stu16添加成功!
stu17添加成功!
stu18添加成功!
stu19添加成功!
stu20添加成功!

Example 3: Guess the commodity price

[root@gcc ~]#vim test6.sh
#!/bin/bash
a=$[$RANDOM  % 1000]         #定义变量a,使用RANDOM函数,随机产生一个数,使用%号是因为RADNOM的取值是0-65535,为了使随机产生的值小一些,所以求模取余出一个数字.
b=0                          #定义b=0是为了下面的while能够结束循环
c=0                          #定义猜的次数从0开始
while [ $b -lt 1 ]           #当$b值小于1时执行一下的循环
do
let c++                      #每猜一次就加1
read -p "请输入商品价格:" i
if [ $i -lt $a  ]
then
   echo "猜小了,再来一次。"
elif [ $i -gt $a ]
then
   echo "猜大了,再来一次。"
elif [ $i -eq $a ]
then
   echo "恭喜,猜对了!"
   b=2                       #使用b=2是为了在猜对了以后打破上面的while循环的命令,即结束while [ $b -lt 1 ] 该命令
fi
done
echo "你一共猜了$c次"         #结束后输出一共猜了多少次

[root@gcc ~]#sh test6.sh 
请输入商品价格:500
猜大了,再来一次。
请输入商品价格:300
猜小了,再来一次。
请输入商品价格:400
猜大了,再来一次。
请输入商品价格:350
猜大了,再来一次。
请输入商品价格:325
猜小了,再来一次。
请输入商品价格:335
猜小了,再来一次。
请输入商品价格:345
猜大了,再来一次。
请输入商品价格:340
猜大了,再来一次。
请输入商品价格:337
猜小了,再来一次。
请输入商品价格:339
猜大了,再来一次。
请输入商品价格:338
恭喜,猜对了!
你一共猜了11次

Example 4: Use a while loop to calculate the sum of all integers 1-100

[root@gcc?~]#vim test7.sh
#!/bin/bash
a=1
sum=0
while [ $a -le 100 ]            #定义变量a的循环范围为1-100
do
  sum=$[$sum+$a]
  let a++                       #a每次加1
done
echo $sum

[root@gcc ~]#sh test7.sh 
5050

Three, untli loop statement

The structure of the until statement
repeatedly tests a certain condition, and executes repeatedly as long as the condition is not established

until 条件测试操作
do
 命令序列
done
while 未超过10
do
 数字依次增加
done

Insert picture description here
Example 1: Use the until loop statement to calculate the sum of all integers from 1 to 100

[root@gcc ~]#vim test8.sh
#!/bin/bash
a=1
sum=0
until [ $a -gt 100 ]        #反向思维,成立时退出,不成立时继续
do
  sum=$[$sum+$a]
  let a++
done
echo $sum

[root@gcc ~]#sh test8.sh 
5050

Four, continue and break

(1) The difference and function of break and continue

Both break and continue are used to control the loop structure, mainly to stop the loop.

1. Break
Sometimes we want to terminate the loop when a certain condition occurs instead of waiting until the loop condition is false.
At this time we can use break to complete. Break is used to completely end a loop, jump out of the loop body and execute the statement following the loop.

2. continue
Continue and break are a bit similar, the difference is that continue only terminates this loop, and then executes the following loop, break completely terminates the loop.
It can be understood that continue means skip the remaining statements in the current loop and execute the next loop.

(二)、break

1. Break statement: The
break statement is used to terminate the execution of the entire loop.

2. The syntax
break
will be used to exit the loop with the following break statement:

break n
where n specifies the nth closed loop to exit.

3. Example:
Stop as soon as it becomes 5 cycles:

[root@gcc ~]#vim test9.sh
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
   echo $a
   if [ $a -eq 5 ]
   then
      break
   fi
   a=`expr $a + 1`
done

[root@gcc ~]#sh test9.sh      #结果在5时结束
0
1
2
3
4
5

(Three), continue

The continue statement is similar to the break command, but it causes the current iteration of the loop to exit instead of the entire loop.
This parameter is useful when an error has occurred, but you want to try to execute the next loop iteration.

1. The syntax
continue
is the same as the break statement. An integer parameter can give the continue command to skip the nested loop command.

continue n
where n specifies the nth closed loop continue.

2. Examples:

[root@gcc ~]#vim demo1.sh
#!/bin/bash
#!/bin/bash
for i in {1..9}
do
    if [ $i -eq 4 ];then
        continue
    else
        echo $i
    fi
 
    if [ $i -eq 6 ];then
        break
    fi
done

[root@gcc ~]#sh demo1.sh      #发现到4的时候直接跳过了,因为continue的作用
1
2
3
5
6                             #到6的时候终止了,时因为break的作用

Five, echo related escape characters

echo -n     表示不换行输出
echo -e     输出转义符,将转义后的内容输出到屏幕上

常用转义符:
\b   转义后相当于按退格键(backspace) ,但前提是"b"后面存在字符; "\b"表示删除前一个字符, "\bb"表示删除前两个字符。
\c   不换行输出,在"\c"后面不存在字符的情况下,作用相当于echo-n;但是当"\c"后面仍然存在字符时, "\c"后面的字符将不会被输出。
\n   换行,被输出的字符从"\n"处开始另起一行
\f   换行,但是换行后的新行的开头位置连接着上一行的行尾;
\v   与\f相同
\t   转以后表示插入tab,即横向制表符;
\r   光标移至行首,但不换行,相当于使用"\r"以后的字符覆盖"1r"之前同等长度的字符;但是当"r"后面不存在任何字符时, "\r"前面的字符不会被覆盖
\\   表示插入""本身:
[root@gcc ~]#echo -e "123\b456"
12456
[root@gcc ~]#echo -e "123\c456"
123[root@gcc ~]#^C
[root@gcc ~]#echo -e "123\n456"
123
456
[root@gcc ~]#echo -e "123\f456"
123
   456
[root@gcc ~]#echo -e "123\v456"
123
   456
[root@gcc ~]#echo -e "123\t456"
123	456
[root@gcc ~]#echo -e "123\r456"
456
[root@gcc ~]#echo -e "123\\456"
123\456

Guess you like

Origin blog.csdn.net/Gengchenchen/article/details/111314488