shell编程-循环结构

shell编程-循环结构

shell循环-for语句
for i in {取值范围}  #for是关键字 i是变量名 in是关键字
do                  #循环体的开始
				循环体
done                #循环体的结束
实战1:
[root@linux-server script]# vim for.sh
#!/usr/bin/env bash
#
# Author:
# Date: 2019/**/**
for i in {1..100} 
do
	echo $i 
done
[root@linux-server script]# vim for1.sh
#!/bin/bash
for (( i=1;i <= 5;i++ ))
do
				echo "$i"
done
[root@linux-server script]# chmod +x for1.sh 
[root@linux-server script]# ./for1.sh
参数解释:
默认值 i=1 
条件  i<=多少?取决于定义,为用户输入的变量,先条件成立在执行命令
增幅  i++  执行一次加一

区别:
i++===先赋值在运算
++i===先运算在赋值
例子
[root@localhost script]# i=1
[root@localhost script]# h=1
[root@localhost script]# let x=i++
[root@localhost script]# echo $x
1
[root@localhost script]# echo $i
2
[root@localhost script]# let y=++h
[root@localhost script]# echo $y
2
[root@localhost script]# echo $h
2

测试成产环境的主机存活性,将up的ip保存在一个文件中,将down的ip保存在一个文件中

[root@linux-server script]# vim ip.sh
#!/usr/bin/env bash
# Author: 
src_ip="192.168.246"
for i in {2..254}
do
        {
        ping -c1 $src_ip.$i &>/dev/null
        if [ $? -eq 0 ];then
                echo "alive: $src_ip.$i" >> ip_up.txt
                echo "alive: $src_ip.$i"
        else
                echo "down: $src_ip.$i" >> ip_down.txt
                echo "down: $src_ip.$i"
        fi
        } &
done
wait
echo "finish..."
[root@linux-server script]# chmod +x ip.sh 
[root@linux-server script]# ./ip.sh
参数详解:
wait:等待上面命令后台执行结束后(即上一个的进程终止),在执行下面的echo命令

for循环批量创建用户

[root@linux-server script]# vim user.sh
#!/usr/bin/bash
read -p "请设置用户名/数量/密码: " prefix num pass
cat <<-EOF
用户前缀:$prefix
用户数量:$num
用户密码:$pass
EOF
for i in $(seq 1 $num)
do
user=$prefix$i
id $user &> /dev/null
if [ $? -eq 0 ];then
        echo "$user is already exist!"
        exit 0
else
        useradd $user &> /dev/null
        echo $pass | passwd --stdin $user &>/dev/null
fi
done
echo "starting create users..."
[root@linux-server script]# chmod +x user.sh 
[root@linux-server script]# ./user.sh

参数详解:
seq 打印序列号,只跟数字
seq 命令用于产生从某个数到另外一个数之间的所有整数。
打印奇数: # seq 1  2  10:表示1到10以内的奇数,2是步长,因为中间隔2.
seq  -w $num  :-w 所有数取最宽的宽度,前面没有的自动补零。

seq命令的原理就不说了,这里说说为什么不能在{ }中使用变量。其实原因写在bash的man手册中:
大意是说,Bash中会最先展开{ }中的内容,这个时候$NUM还不会被具体的值替代,所以是i在循环中读取的是‘{1..$NUM}’的一个完整的字符串,输出时$NUM会被10替代,就有了'{1..10}'这样的结果。
shell 循环while语句
while 条件   #while关键字,条件和if的条件一样,#while循环当条件为真的时候循环同时会一直循环,也就所说的死循环,为假时不循环
do
		循环体
done
#注意:while循环处理文件里面的行比较擅长,不管有没有空格都是一行。

案例:
# vim c.sh
#!/usr/bin/bash
i=1
while [ $i -lt 50 ]
do
        echo $i
done

注意观察,#请问如何能够自动终止
#在shell中,let命令用于指定算术运算,即 let expr

完善系统工具的输出及操作性

#通过一个文件批量创建用户:
#背景:写一个脚本,满足以下需求及应用,如一个文件的内容如下,根据文件内容实现批量创建用户,第一列为用户名,第二列为密码
[root@localhost script]# vim user_pass.txt #创建用户和密码文件
user1 qfedu123
user2 qfedu456
user3 qfedu567
user4 qfedu789
user5 qfedu012
[root@localhost script]# vim create_user.sh #编写脚本
#!/usr/bin/bash

[ $UID -ne 0 ] && exit 1
while read line
do
        user=`echo $line | awk '{print $1}'`
        pass=`echo $line | awk '{print $2}'`
        id $user &> /dev/null || useradd $user && echo $pass | passwd $user --stdin
done < /opt/test/script/user_pass.txt
[root@localhost script]# chmod +x create_user.sh 
[root@localhost script]# bash create_user.sh

案例二:
[root@linux-server script]# vim while.sh
#!/usr/bin/env bash
#
# Author:
while 1>0
do
cat <<-EOF 
+-------------------------------------------------------------------------+ 
|                            System_tools V1.0                            | 
+-------------------------------------------------------------------------+
|                      a. Stop And Disabled Firewalld.                    |
|                      b. Disabled SELinux Secure System.                 |
|                      c. Install Apache Service.                         |
|                      d. Quit                                            | 
+-------------------------------------------------------------------------+
EOF
echo " Please input your select: " && read var
case "$var" in
				"a")
        			systemctl stop firewalld && systemctl disable firewalld
							;; 
				"b")
				sed -ri s/SELINUX=enforcing/SELINUX=disabled/g /etc/selinux/config
							;; 
				"c")
				yum -y install httpd httpd-tools
							;; 
				"d")
				exit
				;; 
				  *)
				echo "请按照上方提供的选项输入!!!"
				;; 
esac
if [ $? -eq 0 ];then 
	clear
else
        echo "Warning: Your program exist ERROR!!!"
        break
fi 
done
[root@linux-server script]# chmod +x while.sh 
[root@linux-server script]# ./while.sh

案例三:嵌套循环
[root@localhost script]# vim test4.sh
#!/usr/bin/bash
for i in {1..100}
do
while [ $i -lt 50 ]
do
        echo $i
        #let i++
done
done
[root@localhost script]# chmod +x test4.sh
[root@localhost script]# bash test4.sh
##### shell循环until语句

```shell
until 条件   #当后面的条件表达式为假的时候的才循环,为真的时候就停止了
do
循环体
done
[root@linux-server script]# cat until.sh 
#!/bin/bash
x=1
until [ $x -ge 10 ]
do
		echo $x
		x=`expr $x + 1` 
done

x=1
while [ ! $x -ge 10 ]
do
		echo $x
		x=`expr $x + 1`
done
[root@linux-server script]# chmod +x until.sh 
[root@linux-server script]# ./until.sh
参数解释:
expr命令可以实现数值运算、数值或字符串比较、字符串匹配、字符串提取、字符串长度计算等功能
shell 循环控制shift、continue、break、exit
shift命令
#位置参数可以用shift命令左移。比如shift 3表示原来的$4现在变成$1,原来的$5现在变成$2等等,原来的$1、$2、$3丢弃,$0不移动。不带参数的shift命令相当于shift 1。
#对于位置变量或命令行参数,其个数必须是确定的,或者当Shell程序不知道其个数时,可以把所有参数一起赋值给变量 $*。
若用户要求 Shell 在不知道位置变量个数的情况下,还能逐个的把参数一一处理,也就是在 $1 后为 $2,在 $2 后面为 $3 等,则需要用shift把所有参数变成$1
#测试 shift 命令(x_shift3.sh)

[root@linux-server script]# cat x_shift3.sh 
#!/bin/bash
shift
echo "第一个位置参数: $1"
[root@linux-server script]# bash x_shift3.sh 2 3 
第一个位置参数: 3

#测试 shift 命令(x_shift.sh) 
[root@linux-server script]# vim x_shift.sh
#!/bin/bash
until [ $# -eq 0 ]
do
echo "第一个参数为: $1 参数个数为: $#" 
shift
done
执行以上程序: 
[root@linux-server script]# bash x_shift3.sh 1 2 3 4
结果显示如下:
第一个参数为: 1 参数个数为: 4 
第一个参数为: 2 参数个数为: 3 
第一个参数为: 3 参数个数为: 2 
第一个参数为: 4 参数个数为: 1

从上可知 shift 命令每执行一次,变量的个数($#)减一,而变量值提前一位



continue、break、exit命令
Linux脚本中的break continue exit return 

break
结束并退出本次循环

continue 
在循环中不执行continue下面的代码,转而进入下一轮循环

exit
退出脚本
常带一个整数给系统,如 exit 0

检测:
[root@localhost script]# vim break.sh
#!/usr/bin/bash
for i in {1..10}
do
if [ $i -eq 7 ];then
        continue
        #break
        #exit 34
else
        echo $i
fi
echo "本次输出结束"
done
echo "脚本结束循环"

#可理解为:break是立马跳出循环;continue是跳出当前条件循环,继续下一轮条件循环;exit是直接退出整个脚本 
例如: 

在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell使用两个命令来实现该功能:break和continue。 

break命令
break命令允许跳出所有循环(终止执行后面的所有循环)。
下面的例子中,脚本进入死循环直至用户输入数字大于5。要跳出这个循环,返回到shell提示符下,需要使用break命令。 
代码如下:
[root@linux-server script]# vim break.sh
#!/bin/bash
while :
do
echo -n "Input a number between 1 to 5: " 
read aNum
case $aNum in
        1|2|3|4|5)
        echo "Your number is $aNum!"
        ;;
        *)
        echo "You do not select a number between 1 to 5, game is over!"
        break 
        ;;
esac
done

#将break注释掉观察结果

案例2:continue
continue命令
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。
[root@linux-server script]# bash break.sh
 
对上面的例子进行修改:
代码如下:
[root@linux-server script]# vim break1.sh
#!/bin/bash
while :  #默认为真
do
echo -n "Input a number between 1 to 5: " 
read aNum
case $aNum in
        1|2|3|4|5)
        echo "Your number is $aNum!"
        ;;
        *)
        echo "You do not select a number between 1 to 5, game is over!"
        continue 
        ;;
esac
done
[root@linux-server script]# bash break1.sh
#运行代码发现,当输入大于5的数字时,该例中的循环不会结束.


break和exit的区别
[root@linux-server script]# vim case07.sh 
#!/bin/bash
while true
do
read -p "请输入[1/2]" num1
case $num1 in
        1)
        echo $num1
        ;;
        2)
        while true 
        do
        read -p "再次输入[1/2]:" num2
        case $num2 in
                1)
                echo $num2
                ;;
                2)
                break;;             #将此处换成exit,再次尝试
                #exit;;
        esac
        done
esac
done
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值