循环语句for基本概述

01. for循环基础语法

for 变量名 in [ 取值列表 ]do 循环体done

02. for循环基本使用示例

#取值列表有多种取值方式,可以直接读取in后面的值,默认以空格做分割符

  1. [root@qiudao /scripts]# cat for-1.sh
  2. #!/bin/bash
  3. for var in file1 file2 file3do
  4. echo "The text is $var"
  5. done
  6. [root@qiudao /scripts]# sh for-1.sh
  7. The text is file1
  8. The text is file2
  9. The text is file3

03. for循环基本使用示例,列表中的复杂值,可以使用引号或转义字符""来加以约束

  1. [root@qiudao /scripts]# cat for-2.sh
  2. #!/bin/bash
  3. for var in file1 "file2 hello" file3
  4. do
  5. echo "The text is $var"
  6. done
  7. [root@qiudao /scripts]# sh for-2.sh
  8. The text is file1
  9. The text is file2 hello
  10. The text is file3
  11. #转义字符
  12. [root@qiudao /scripts]# cat for-3.sh
  13. #!/bin/bash
  14. for var in file1 file \'2
  15. do
  16. echo "The text is $var"
  17. done
  18. [root@qiudao /scripts]# sh for-3.sh
  19. The text is file1
  20. The text is file
  21. The text is '2

04. for循环基本使用示例,从变量中取值

  1. [root@qiudao /scripts]# cat for-4.sh
  2. #!/bin/bash
  3. list="file1 file2 file3"
  4. for var in $list
  5. do
  6. echo $var
  7. done
  8. [root@qiudao /scripts]# sh for-4.sh
  9. file1
  10. file2
  11. file3

05. for循环基本使用示例,从命令中取值

  1. [root@qiudao /scripts]# cat for-5.sh
  2. #!/bin/bash
  3. for var in `cat /etc/hosts`
  4. do
  5. echo $var
  6. done
  7. [root@qiudao /scripts]# sh for-5.sh
  8. 127.0.0.1localhostlocalhost.localdomainlocalhost4localhost4.localdomain4::1localhostlocalhost.localdomainlocalhost6localhost6.localdomain6

06. for循环基本使用示例,自定义Shell分隔符。默认情况以空格为分隔符。通过IFS来自定义分隔符

  1. #以冒号做分隔符 IFS=:
  2. #以冒号,分号和双引号作为字段分隔符 IFS=:;"
  3. #以换行符作为字段分隔符 IFS=$'\n'
  4. #以回车为换行符
  5. [root@qiudao /scripts]# cat for-6.sh
  6. #!/bin/bash
  7. IFS=$'\n'
  8. for var in `cat /etc/hosts`
  9. do
  10.     echo $var
  11. done
  12. [root@qiudao /scripts]# sh for-6.sh
  13. 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
  14. ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
  15. #以:为分隔符
  16. [root@qiudao /scripts]# cat for-7.sh
  17. #!/bin/bash
  18. IFS=:
  19. list=`head -1 /etc/passwd`
  20. for var in $list
  21. do
  22.     echo $var
  23. done
  24. [root@qiudao /scripts]# sh for-7.sh
  25. root
  26. x
  27. 0
  28. 0
  29. root
  30. /root
  31. /bin/bash

07. for循环基本使用示例,C语言风格的for

#语法格式for ((i=0;i<10;i++))do commandsdone

#例1,单个变量,输出1到10之间的数字[root@qiudao /scripts]# cat for-8.sh#!/bin/bashfor ((i=0;i<10;i++))doecho num is $idone

[root@qiudao /scripts]# sh for-8.shnum is 0num is 1num is 2num is 3num is 4num is 5num is 6num is 7num is 8num is 9

例2,多个变量,同时输出1-9的升序和降序

解法一:

[root@qiudao /scripts]# cat for-9.sh

  1. #!/bin/bash
  2. for ((a=1,b=9;a<10;a++,b--))
  3. do
  4. echo num is $a $b
  5. done
  6. [root@qiudao /scripts]# sh for-9.sh
  7. num is 1 9
  8. num is 2 8
  9. num is 3 7
  10. num is 4 6
  11. num is 5 5
  12. num is 6 4
  13. num is 7 3
  14. num is 8 2
  15. num is 9 1
  16. #解法二:
  17. [root@qiudao /scripts]# cat for-10.sh
  18. #!/bin/bash
  19. a=0
  20. b=10
  21. for i in {1..9}
  22. do
  23. let a++;
  24. let b--;
  25. echo num is $a $b
  26. done
  27. [root@qiudao /scripts]# sh for-10.sh
  28. num is 1 9
  29. num is 2 8
  30. num is 3 7
  31. num is 4 6
  32. num is 5 5
  33. num is 6 4
  34. num is 7 3
  35. num is 8 2
  36. num is 9 1

2. 循环语句for场景示例

01. for循环场景示例一:通过读入文件中的用户,进行批量添加用户。

  1. [root@qiudao /scripts]# cat for-11.sh
  2. #!/usr/bin/bash
  3. for i in $(cat user.txt)
  4. do
  5. useradd $i &>/dev/null
  6. if [ $? -eq 0 ];then
  7. echo $i 用户创建成功
  8. else
  9. echo $i 用户已存在
  10. fi
  11. done
  12. [root@qiudao /scripts]# sh for-11.shtt1 用户创建成功tt2 用户创建成功tt3 用户创建成功tt4 用户创建成功tt5 用户创建成功tt6 用户创建成功tt7 用户创建成功tt8 用户创建成功tt9 用户创建成功tt10 用户创建成功

02. for循环场景示例二:通过读入文件中的用户:密码,进行批量添加用户。

  1. [root@qiudao /scripts]# cat user.txt
  2. user01:suibian
  3. user02:suibian2
  4. user03:suibian3
  5. [root@qiudao /scripts]# cat for-12.sh
  6. #!/usr/bin/bash
  7. for i in $(cat user.txt)
  8. do
  9.     #1.取出来的行,使用awk进行分隔,然后分别赋值给user和pass两个变量
  10.     user=$(echo $i|awk -F ":" '{print $1}')
  11.     pass=$(echo $i|awk -F ":" '{print $2}')
  12.     
  13.     #2.判断用户是否存在
  14.     id $user &>/dev/null
  15.   
  16.     #3.用户存在则提示已存在,否则添加用户,然后使用pass变量设定对应的密码
  17.     if [ $? -eq 0 ];then
  18.         echo "$user 已存在"
  19.     else
  20.         useradd $user
  21.         echo "$pass" | passwd --stdin $user &>/dev/null
  22.         echo "用户$user 创建成功!"
  23.     fi
  24. done
  25. [root@qiudao /scripts]# sh for-12.sh
  26. 用户user1 创建成功!
  27. 用户user2 创建成功!
  28. 用户user3 创建成功!

03. for循环场景示例三:批量创建用户脚本,需要用户输入创建的用户数量,以及需要用户输入创建的前缀。

  1. [root@qiudao /scripts]# cat for-13.sh
  2. #!/usr/bin/bash
  3. read -p "请输入你要创建的用户前缀: " user_qz
  4. read -p "请输入你要创建的用户数量: " user_num
  5. echo "你创建的用户是 ${user_qz}1 ..${user_qz}${user_num}"
  6. read -p "你确定要创建以上用户吗?[ y/n ] " readly
  7. case $readly in
  8.     y)
  9.         for i in $(seq $user_num)
  10.         do
  11.             user=${user_qz}${i}
  12.             id $user &>/dev/null
  13.             if [ $? -eq 0 ];then
  14.                 echo "useradd: user $user already exists"
  15.             else
  16.                 useradd $user
  17.                 echo "useradd: user $user add successfully."
  18.             fi
  19.         done
  20.         ;;
  21.     n)
  22.         echo "你想好了再创建......"
  23.         exit
  24.         ;;
  25.     *)
  26.         echo "请不要乱输入...."
  27.         exit
  28. esac

04. for循环场景示例四:批量创建用户脚本,需要用户输入创建的用户数量(必须是整数),同时还需要用户输入前缀(前缀不能为空)。例如:前缀qls,个数10,代表创建qls1~qls10,总共10个用户。注意:此脚本仅root可执行,其他人无权限执行。

  1. [root@qiudao /scripts]# cat for-14.sh#!/usr/bin/bashif [ ! $UID -eq 0 ] && [ ! $USER == "root" ];then echo "无权限执行......" exitfi
  2. read -p "请输入你要创建的用户前缀: " user_qzif [ -z $user_qz ];then echo "请输入有效的值....." exitfi
  3. read -p "请输入你要创建的用户数量: " user_numif [[ ! $user_num =~ ^[0-9]+$ ]];then echo "请输入整数" exitfi
  4. echo "你创建的用户是 ${user_qz}1 ..${user_qz}${user_num}"read -p "你确定要创建以上用户吗?[ y/n ] " readly
  5. case $readly in y|yes|YES) for i in $(seq $user_num) do user=${user_qz}${i} id $user &>/dev/null if [ $? -eq 0 ];then echo "useradd: user $user already exists" else useradd $user echo "useradd: user $user add successfully." fi done
  6. ;; n|no|NO) echo "你想好了再创建......" exit ;; *) echo "请不要乱输!" exitesac

05. for循环场景示例五:批量创建用户脚本,需要用户输入创建的用户数量(必须是整数),同时还需要用户输入前缀(前缀不能为空)。例如:前缀qls,个数10,代表创建qls1~qls10,总共10个用户。注意:此脚本仅root可执行,其他人无权限执行。用户的密码使用随机密码,并保存到某一个指定的文件中。

  1. [root@backup scripts]# cat 3.sh
  2. #!/bin/bash
  3. if [ ! $USER == "root" ] && [ ! $UID -eq 0 ];then
  4. echo "该用户没有执行权限"
  5. exit
  6. fi
  7. read -p "请输入你想要的前缀:" dir
  8. if [ -z $dir ];then
  9. echo " 输入不能为空,不支持"
  10. exit
  11. fi
  12. if [[ ! $dir =~ ^[a-Z]+$ ]];then
  13. echo "输入错误,请输入字母:"
  14. exit
  15. fi
  16. read -p "请输入创建用户的数量:" num
  17. if [ -z $num ];then
  18. echo "不能为空"
  19. exit
  20. else
  21. if [[ ! $num =~ ^[0-9]+$ ]];then
  22. echo "请输入数字为整数"
  23. exit
  24. fi
  25. fi
  26. read -p "你创建的用户为${dir}1..${dir}n${num},确认创建[y|n]: " rc
  27. case $rc in
  28. y|Y|yes)
  29. for i in $(seq $num)
  30. do
  31. user=${dir}${num}
  32. pass=$(echo $((RANDOM)) |md5sum |cut -c 2-24)
  33. id $user &>/dev/null
  34. if [ $? -eq 0 ];then
  35. echo "用户已经存在"
  36. else
  37. useradd $user &>/dev/null && echo $pass |passwd --stdin $user &>/dev/null
  38. if [ $? -eq 0 ];then
  39. echo "用户$user 创建成功,密码ok"
  40. echo "用户:$user 密码:$pass" >>/tmp/q.txt
  41. echo "用户密码文件在/tmp/q.txt"
  42. else
  43. echo "用户创建失败"
  44. exit
  45. fi
  46. fi
  47. done
  48. ;;
  49. n|N|no)
  50. echo "你不想创建,推迟"
  51. exit
  52. ;;
  53. *)
  54. echo "请输入正确的格式[y|n]"
  55. exit
  56. esac

06. for循环场景示例六:批量删除(用户需要输入用户前缀及数字),有就删除,没有就提示没有该用户。

  1. [root@backup scripts]# cat 4.sh
  2. #!/bin/bash
  3. if [ ! $USER == "root" ] && [ ! $UID -eq 0 ];then
  4. echo "该用户没有执行权限"
  5. exit
  6. fi
  7. read -p "请输入你想要删除的前缀:" dir
  8. if [ -z $dir ];then
  9. echo " 输入不能为空,不支持"
  10. exit
  11. fi
  12. if [[ ! $dir =~ ^[a-Z]+$ ]];then
  13. echo "输入错误,请输入字母:"
  14. exit
  15. fi
  16. read -p "请输入想要删除用户的数量:" num
  17. if [ -z $num ];then
  18. echo "不能为空"
  19. exit
  20. else
  21. if [[ ! $num =~ ^[0-9]+$ ]];then
  22. echo "请输入数字为整数"
  23. exit
  24. fi
  25. fi
  26. read -p "你删除的用户为${dir}${num},确认删除[y|n]: " rc
  27. case $rc in
  28. y|Y|yes)
  29. for i in ${dir}${num}
  30. do
  31. user=${dir}${num}
  32. id $user &>/dev/null
  33. if [ $? -eq 0 ];then
  34. userdel $user &>/dev/null
  35. if [ $? -eq 0 ];then
  36. echo "用户$user已删除"
  37. else
  38. echo "用户$user删除失败"
  39. fi
  40. else
  41. echo "用户不存在"
  42. exit
  43. fi
  44. done
  45. ;;
  46. n|N|no)
  47. echo "你不想删除,退出"
  48. exit
  49. ;;
  50. *)
  51. echo "请输入正确的格式[y|n]"
  52. exit
  53. esac

07. for循环场景示例七:批量探测主机存活状态及22端口状态

1)需要用循环,循环254次2)探测主机使用ping命令

  1. [root@backup scripts]# cat 5.sh
  2. #!/bin/bash
  3. for i in {30..50}
  4. do
  5. ip=172.16.1.$i
  6. ping -c 1 -w 1 $ip &>/dev/null
  7. if [ $? -eq 0 ];then
  8. echo "$ip是接通的"
  9. else
  10. echo "$ip是不接通的"
  11. fi
  12. done

08. for循环场景示例八:编写一个上课随机点名脚本。

1.需要有名字2.需要循环的打印这些名单3.随机挑选一个数字进行打印

  1. [root@backup scripts]# cat student.sh
  2. #!/bin/bash
  3. stu_num=`wc -l student.txt|awk '{print $1}'`
  4. for i in $(seq $stu_num)
  5. do
  6. num=$(echo $(( $RANDOM % ${stu_num} +1 )))
  7. sed -n "${num}p" student.txt
  8. sleep 0.2
  9. done
  10. stu_name=$(sed -n "${num}p" student.txt)
  11. echo -e "天选之子: \033[32m ${stu_name}....\033[0m"

09. for循环场景示例九:使用for循环实现数据库的分库分表备份。

  1. [root@backup scripts]# cat mysql.sh
  2. #!/bin/bash
  3. ##############################################################
  4. # File Name: mysql.sh
  5. # Time: 2019-10-22-15:23:08
  6. # Author: qls
  7. # Organization: www.increase93.com
  8. ##############################################################
  9. db_user=root
  10. db_name=`mysql -uroot -e "show databases;"|sed 1d|grep -v .*_schema`
  11. date=`date +%F`
  12. for database in $db_name
  13. do
  14. if [ ! -d /backup/$database ];then
  15. mkdir -p /backup/$database
  16. fi
  17. mysqldump -u$db_user -B $database >/backup/$database/${database}_${date}.sql &>/dev/null
  18. if [ $? -eq 0 ];then
  19. echo "$database备份成功"
  20. db_table=$(mysql -u$db_user -e "use $database;show tables;"|sed 1d)
  21. for tables in $db_table
  22. do
  23. mysqldump -u$db_user $database $tables >/backup/$database/${database}_${tables}_${date}.sql
  24. if [ $? -eq 0 ];then
  25. echo "$db_table表备份成功"
  26. else
  27. echo "$db_table表备份失败"
  28. continue
  29. fi
  30. done
  31. else
  32. echo "数据库$database备份失败"
  33. continue
  34. fi
  35. done
  1. 1.怎么备份数据库 mysqldump -uroot -p123.com --single-transaction -B world > world_database.sql2.怎么备份数据库的表mysqldump -uroot -p123.com --single-transaction world city > world_city_tables.sql3.备份到哪儿/mysql_dump/oldboy/city_2019_07_16.sql
  2. #!/usr/bin/bash
  3. db_name=$(mysql -uroot -p123.com -e "show databases;"|sed 1d |grep -v ".*_schema")
  4. DB_User=root
  5. DB_Pass=123.com
  6. Date=$(date +%F)
  7. for database_name in $db_name
  8. do
  9.     #1.准备每个库的目录
  10.     DB_Path=/mysql_dump/$database_name
  11.     if [ ! -d $DB_Path ];then
  12.         mkdir -p $DB_Path
  13.     fi
  14.     #2.备份数据库
  15.     mysqldump -u$DB_User -p$DB_Pass --single-transaction
  16.     -B $database_name > $DB_Path/${database_name}_${Date}.sql
  17.     echo -e "\033[31m $database_name 数据库
  18. 已经备份完成..... \033[0m"
  19.     
  20.     #3.备份数据库的每一个表
  21.     tb_name=$(mysql -u$DB_User -p$DB_Pass -e "use ${database_name};show tables;"|sed 1d)
  22.     
  23.     #4.批量的备份数据库的表
  24.     for table_name in $tb_name
  25.     do
  26.         #5.备份数据库的表数据
  27.         mysqldump -u$DB_User -p$DB_Pass --si

10. for循环场景示例十:用于判断mysql数据库主从的脚本,需要邮件通知。

  1. 1.判断io线程和sql线程是否都为yes,如果是则成功。2.如果io线程失败,则直接邮件通知,如果sql线程失败,则检查是什么错误状态码,根据状态码修复。3.无法修复,或任何错误代码太复杂建议,直接发邮件通知管理员。
  2. [root@qiudao /scripts]# cat for-20.sh
  3. #!/usr/bin/bash
  4. IO_Status=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Slave_IO_Running/ {print $2}')
  5. SQL_Status=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Slave_SQL_Running/ {print $2}')
  6. slave_sql_error_message(){
  7. mysql -uroot -p123.com -e "show slave status\G"|grep "Last_SQL" > /tmp/sql_err.log
  8. mail -s "MySQL Master SLave SQL Error $(date +%F)" 1176494252@qq.com < /tmp/sql_err.log
  9. echo "邮件通知成功......"
  10. }
  11. slave_io_error_message(){
  12. mysql -uroot -p123.com -e "show slave status\G"|grep "Last_IO" > /tmp/io_err.log
  13. mail -s "MySQL Master SLave IO Error $(date +%F)" 1176494252@qq.com < /tmp/io_err.log
  14. echo "邮件通知成功......"}
  15. if [ $IO_Status == "Yes" ] && [ $SQL_Status == "Yes" ];then
  16. echo "MySQL主从正常"
  17. else
  18. #1.判断IO异常
  19. if [ ! $IO_Status == "Yes" ];then slave_io_error_message
  20. exit
  21. fi
  22. #2.判断SQL异常
  23. if [ ! $SQL_Status == "Yes" ];then
  24. SQL_Err=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Last_SQL_Errno/ {print $2}')
  25. #3.精细化判断主从不同步的问题
  26. case $SQL_Err in
  27. 1007)
  28. echo "主从的SQL出现问题,尝试使用set global sql_slave_skip_counter=1; 跳过错误"
  29. sleep 2
  30. mysql -uroot -p123.com -e "stop slave;set global sql_slave_skip_counter=1;start slave;" SQL_Err_1=$(mysql -uroot -p123.com -e "show slave status\G"|awk '/Last_SQL_Errno/ {print $2}') if [ $SQL_Err_1 -eq 0 ];then
  31. echo "尝试跳过了一次,恢复MySQL数据库成功" else
  32. slave_sql_error_message
  33. fi
  34. ;;
  35. 1032)
  36. slave_sql_error_message
  37. ;;
  38. *)
  39. slav

3. 循环语句while基本概述

while循环语句,只要条件成立就反复执行对应的命令操作,直到命令不成立或为假

01. while循环基础语法

#当条件测试成立(条件测试为真),执行循环体

while 条件测试

do 循环体

done

02. while循环基本使用示例,降序输出10到1的数字

  1. [root@qiudao /scripts]# cat while-1.sh
  2. #!/bin/bash
  3. var=10
  4. while [ $var -gt 0 ]
  5. do
  6. echo $var
  7. var=$[$var-1]done
  8. #简单加法表
  9. [root@qiudao /scripts]# cat while-2.sh
  10. #!/usr/bin/bash
  11. a=1
  12. b=10
  13. while [ $a -le 10 ]
  14. do
  15. sum=$(( $a + $b ))
  16. echo $a + $b = $sum
  17. let a++
  18. let b--
  19. done

03. while循环基本使用示例,输出如下图,两数相乘。

  1. #自增[root@qiudao /scripts]# cat while-3.sh
  2. #!/bin/bash
  3. num=9
  4. while [ $num -ge 1 ]
  5. do
  6. sum=$(( $num * $num ))
  7. echo "$num * $num = $sum"
  8. num=$[$num-1]
  9. done
  10. \#自减[root@qiudao /scripts]# cat while-4.sh
  11. #!/bin/bash
  12. num=1
  13. while [ $num -le 9 ]
  14. do
  15. sum=$(( $num * $num ))
  16. echo "$num * $num = $sum"
  17. num=$[$num+1]
  18. done

4. 循环语句while场景示例

01. 使用while读入文件方式,批量创建用户,while默认按行取值

  1. [root@qiudao /scripts]# cat while-5.sh
  2. #!/usr/bin/bash
  3. while read line
  4. do
  5.     #1.判断用户是否存在
  6.     id $line &>/dev/null
  7.     if [ $? -eq 0 ];then
  8.         echo "User: $line already exists"
  9.     else
  10.         useradd $line &>/dev/null
  11.         echo "User: $line Create Ok"
  12.     fi
  13. done<user.txt
  14. [root@qiudao /scripts]# cat user.txt
  15. ttt1
  16. ttt2
  17. ttt3
  18. ttt4
  19. ttt5
  20. **02.

02. 使用while读入文件方式,批量创建用户以及密码[user:passwd]

使用while读入文件方式,批量创建用户,并赋予一个随机密码**

  1. [root@backup scripts]# cat us.sh
  2. #!/bin/bash
  3. while read line
  4. do
  5. user=`echo $line|awk -F: '{print $1}'`
  6. pass=`echo $line|awk -F: '{print $2}'`
  7. id $user &>/dev/null
  8. if [ $? -eq 0 ];then
  9. echo "$user已经存在"
  10. else
  11. useradd $line &>/dev/null && echo $pass |passwd --stdin $user &>/dev/null
  12. if [ $? -eq 0 ];then
  13. echo "ok"
  14. else
  15. echo "faile"
  16. fi
  17. fi
  18. done < user.txt

04. while循环场景示例:完成如下猜数字游戏

  1. [root@backup scripts]# cat cai.sh
  2. #!/bin/bash
  3. ##############################################################
  4. # File Name: cai.sh
  5. # Time: 2019-10-22-16:51:15
  6. # Author: qls
  7. # Organization: www.increase93.com
  8. ##############################################################
  9. sum=`echo $(( RANDOM % 100 +1 ))`
  10. echo "请输入你猜的整数"
  11. i=0
  12. while true
  13. do
  14. read -p "请输入你猜的数字:" int
  15. if [[ ! $int =~ ^[0-9]+$ ]];then
  16. echo "必须输入整数"
  17. continue
  18. fi
  19. if [ -z $int ];then
  20. echo "不能为空"
  21. continue
  22. fi
  23. if [ $int -gt 100 -o $int -lt 0 ];then
  24. echo "100以内的数字"
  25. continue
  26. fi
  27. if [ $int -gt $sum ];then
  28. echo "猜大了"
  29. elif [ $int -lt $sum ];then
  30. echo "猜小了"
  31. else
  32. echo "ok"
  33. break
  34. fi
  35. let a++
  36. done
  37. echo "总次数 $(( $a +1 ))"

景示例:随机点菜脚本**

  1. [root@backup scripts]# cat tayn.sh
  2. #!/bin/bash
  3. main(){
  4. cat <<EOF
  5. #####################################
  6. 1.糖醋排骨 30
  7. 2.清蒸鲈鱼 50
  8. 3.青椒炒蛋 20
  9. 4.烤羊排 199
  10. 5.结束点菜
  11. ######################################
  12. EOF
  13. }
  14. >caidan.txt
  15. echo "您好!欢迎进入点菜系统"
  16. while true
  17. do
  18. main
  19. read -p "请开始点菜:" dian
  20. case $dian in
  21. 1)
  22. echo "糖醋排骨:价格30元"
  23. echo "糖醋排骨:30" >>caidan.txt
  24. ;;
  25. 2)
  26. echo "清蒸鲈鱼:价格50元"
  27. echo "清蒸鲈鱼:50" >>caidan.txt
  28. ;;
  29. 3)
  30. echo "青椒炒蛋:价格20元"
  31. echo "青椒炒蛋:20" >>caidan.txt
  32. ;;
  33. 4)
  34. echo "烤羊排:价格199元"
  35. echo "烤羊排:199" >>caidan.txt
  36. ;;
  37. 5)
  38. echo "结束点菜,菜品和价格如下"
  39. sort caidan.txt |uniq -c |sort -rn |awk '{print "您点了 "$2"总共"$1""}'
  40. awk -F: '{i+=$2}END{print "总价格:"i"元"}' caidan.txt
  41. exit
  42. ;;
  43. *)
  44. echo "本店无您的需求,抱歉"
  45. continue
  46. esac
  47. done

5. 内置跳出循环语句指令

在我们使用循环语句进行循环的过程中,有时候需要在未达到循环结束条件时强制跳出循环,那么Shell给我们提供了内置方法来实现该功能:exit、break、continue

01. exit,退出整个程序

  1. [root@qiudao /scripts]# cat for-exit.sh
  2. #!/bin/bash
  3. for i in {1..3}
  4. do
  5. echo "123"
  6. exit
  7. echo "456"
  8. done
  9. echo "done ......"
  10. \#执行结果[root@qiudao /scripts]# sh for-exit.sh
  11. 123

02. break,结束当前循环,或跳出本层循环

  1. [root@qiudao /scripts]# cat for-break.sh
  2. #!/bin/bash
  3. for i in {1..3}
  4. do
  5. echo "123"
  6. break
  7. echo "456"
  8. done
  9. echo "done ......"
  10. \#执行结果[root@qiudao /scripts]# sh for-break.sh
  11. 123
  12. done ......

03. continue,忽略本次循环剩余的代码,直接进行下一次循环。

  1. [root@qiudao /scripts]# cat for-continue.sh
  2. #!/bin/bash
  3. for i in {1..3}do
  4. echo "123"
  5. continue
  6. echo "456"
  7. done
  8. echo "done ......"
  9. \#执行结果[root@qiudao /scripts]# sh for-continue.sh
  10. 123
  11. 123
  12. 123
  13. done ......

04. 习题:先扫描内网网段所有主机,存活的则下发当前主机的公钥。

  1. [root@qiudao /scripts]# cat key.sh
  2. #!/bin/bash

删除旧的密钥对

  1. rm -f ~/.ssh/id_rsa*

创建密钥对

  1. ssh-keygen -t rsa -f ~/.ssh/id_rsa -N "" &>/dev/null

批量分发公钥的操作

  1. for ip in {2..10}
  2. do
  3. ping -W1 -c1 172.16.1.$ip &>/dev/null
  4. if [ $? -eq 0 ];then
  5.      #z注意密码根端口
  6.      sshpass -p123 ssh-copy-id -p2222 -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 172.16.1.$ip &>/dev/null
  7.      if [ $? -eq 0 ];then
  8.         echo -e "\033[32mhost 172.16.1.$ip Distribution of the secret key Success!!! \033[0m"
  9.         echo
  10.     else
  11.         echo -e "\033[31mhost 172.16.1.$ip Distribution of the secret key Failed !!! \033[0m"
  12.         echo
  13.         fi
  14. else
  15.     echo -e "\033[31mhost 172.16.1.$ip Destination Host Unreachable! \033[0m"
  16.     continue
  17. fi
  18. done

循环语句for基本概述的更多相关文章

  1. Go 循环语句

    Go 循环语句 一.概述 在不少实际问题中有许多具有规律性的重复操作,因此在程序中就需要重复执行某些语句. 循环程序的流程图: Go 语言提供了以下几种类型循环处理语句: 循环类型 描述 for 循环 ...

  2. 循环语句(for,while,do……while),方法概述

    循环结构 分类:for,while,do……while (1)for语句 格式: for(初始化表达式:条件表达式:循环后的操作表达式){ 循环体: } 执行流程: a.执行初始化语句 b.执行判断条 ...

  3. javascript语句——条件语句、循环语句和跳转语句

    × 目录 [1]条件语句 [2]循环语句 [3]跳转语句 前面的话 默认情况下,javascript解释器依照语句的编写顺序依次执行.而javascript中的很多语句可以改变语句的默认执行顺序.本文 ...

  4. 你可能不知道的java、python、JavaScript以及jquary循环语句的区别

    一.概述 java循环语句分为四种形式,分别是 while, do/while, for, foreach: python中循环语句有两种,while,for: JavaScript中循环语句有四种, ...

  5. 【Java基础】【04循环语句&方法】

    04.01_Java语言基础(循环结构概述和for语句的格式及其使用) A:循环结构的分类 for,while,do...while B:循环结构for语句的格式: for(初始化表达式;条件表达式; ...

  6. Java流程控制之循环语句

    循环概述 循环语句可以在满足循环条件的情况下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则循环将 ...

  7. JavaSE04-Switch&循环语句

    1.Switch 格式: 1 switch (表达式) { 2 case 1: 3 语句体1; 4 break; 5 case 2: 6 语句体2; 7 break; 8 ... 9 default: ...

  8. while,do while,for循环语句

    循环语句 循环包含三大语句-----while语句 do while语句 for语句 循环三要素 初始值(初始的变量值) 迭代量(基于初始值的改变) 条件(基于初始值的判断) while语句 var ...

  9. 【python之路4】循环语句之while

    1.while 循环语句 #!/usr/bin/env python # -*- coding:utf-8 -*- import time bol = True while bol: print '1 ...

随机推荐

  1. 基于MbedTLS的AES加密实现,含STM32H7和STM32F4的实现例程

    说明: 1.mbedTLS的前身是PolarSSL,开源免费. 主要提供了的SSL/TLS支持(在传输层对网络进行加密),各种加密算法,各种哈希算法,随机数生成以及X.509(密码学里公钥证书的格式标 ...

  2. openshift安装部署

    前置准备工作: 1.每台主机准备好有公钥在 /root/.ssh/authorized_keys,私钥则存放在第一台主机的/root/.ssh/id_rsa 2.确定每台主机的私网IP地址是固定的. ...

  3. (3)一起来看下使用mybatis框架的select语句的源码执行流程吧

    本文是作者原创,版权归作者所有.若要转载,请注明出处.本文以简单的select语句为例,只贴我觉得比较重要的源码,其他不重要非关键的就不贴了 主流程和insert语句差不多,这里主要讲不同的流程,前面 ...

  4. MongoDB(二):在Windows环境安装MongoDB

    1. 在Windows环境安装 1.1 MongoDB下载 要在Windows上安装MongoDB,首先打开MongoDB官网:https://www.mongodb.com/download-cen ...

  5. Python中通过csv的writerow输出的内容有多余的空行两种方法

    第一种方法 如下生成的csv文件会有多个空行 import csv #python2可以用file替代open with open("test.csv","w" ...

  6. HTML+CSS基础知识点简要汇总(思维导图)

  7. diango中让装了装饰器的函数的名字不是inner,而是原来的名字

    让装了装饰器的函数的名字不是inner,而是原来的名字 from functools import wraps def wrapper(func): @wraps(func) # 复制了原来函数的名字 ...

  8. 开启docker

    systemctl daemon-reload systemctl restart docker.service

  9. Cocos2d-x3.0网络通信学习(一)

    配置:win7+Cocos2d-x.3.0+VS2012 摘要:建立基本的http通信并得到返回信息. 一.添加项目与编译库 1.添加头文件 在需要用到Http网络相关类的文件中加入头文件 #incl ...

  10. gunicorn Python部署应用

    对于flask应用 启动命令为 python app.py 使用gunicorn启动 pip install gunicorn python gunicorn --workers=7 switch_a ...