就业班 第二阶段 2401--3.28 day8 shell之循环控制

七、shell编程-循环结构

shell循环-for语句
for i in {取值范围}    # for 关键字  i 变量名 in 关键字  取值范围格式 1 2 3 4 5
do                    # do 循环体的开始
                循环体
done                  # done 循环体的结束 
#!/usr/bin/env bash
#
# Author:
# Date: 2019/**/**
for i in {1..100} 
do
                echo $i 
done
#!/bin/bash         # 类似c语言的循环方式
for (( i=1;i <= 5;i++ ))
do
                echo "$i"
done

测试生产环境的主机存活性

#!/usr/bin/env bash #
# Author:       #{}&  并发
>ip_alive.txt     # 在执行脚本之前,先将文件清空
>ip_down.txt
segment="192.168.161" 
for i in {2..254}
do
        {
        ping -c1 $segment.$i &>/dev/null 
        if [ $? -eq 0 ];then
                        printf "alive: $segment.$i\n" >>ip_alive.txt
        else
                        printf "down: $segment.$i\n" >>ip_down.txt
        fi
        }& 
done
wait    #等待循环结束后,执行下面操作
echo "finish..."

for循环批量创建用户

#!/bin/bash 
while :     #死循环
do
read -p "请设置用户前缀/数量/密码: " prefix num pass 
cat <<-EOF                 # 打印到屏幕
用户前缀:$prefix
用户数量:$num
用户密码:$pass
EOF
read -p "是否确认创建:[Y/N]" action 
if [ $action = Y ];then
     "starting create users..." 
     break
fi
done
for i in `seq -w $num`
do
    user=$prefix$i
    id $user &>/dev/null 
    if [ $? -eq 0 ];then
          echo "$user  is already exist"
    else
          useradd $user
          echo $pass | passwd --stdin $user &>/dev/null  # 用户密码设置不需要交互
    fi 
done
shell 循环while语句
while 条件    # while 关键字  条件  [ $1 -lt 10 ] ,while循环,条件为真的情况下,会循环
do
        循环体
done

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

创建一个文件里面的用户
#!/bin/bash
while read user
do
        id $user &>/dev/null 
        if [ $? -eq 0 ];then
                echo "$user is already exists"
        else
                useradd $user
                echo "create $user successfully"
        fi
done < user.txt
​
​
#!/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
​
练习题:
输出用户输入的参数,直到用户输入 "end" 结束循环
​
#!/usr/bin/bash
while 2>1
do
    read -p "请输入: " word
    if [ $word != 'end' ];then
        echo "$word"
    else
        echo "退出循环"
        break
    fi
done
shell循环until语句
until 条件 # 当后面的条件表达式,为假的时候进行循环,当他为真了就停止循环了。
do
循环体
done
[root@newrain ~]# 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
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@newrain shell]# cat x_shift3.sh 
#!/bin/bash
shift
echo "第一个位置参数: $1"
[root@newrain shell]# bash x_shift3.sh 2 3
第一个位置参数: 3
​
#测试 shift 命令(x_shift.sh) 
#!/bin/bash
until [ $# -eq 0 ]
do
echo "第一个参数为: $1 参数个数为: $#" 
shift
done
执行以上程序x_shift.sh: 
$./x_shift.sh 1 2 3 4
结果显示如下:
第一个参数为: 1 参数个数为: 4 
第一个参数为: 2 参数个数为: 3 
第一个参数为: 3 参数个数为: 2 
第一个参数为: 4 参数个数为: 1
​
从上可知 shift 命令每执行一次,变量的个数($#)减一,而变量值提前一位
​
用 until 和 shift 命令计算所有命令行参数的和。 
#shift 上档命令的应用(x_shift2.sh)
sum=0
​
until [ $# -eq 0 ] 
do
        sum=`expr $sum + $1`
        shift 
done
echo "sum is: $sum"
执行上述程序: 
        $x_shift2.sh 10 20 15
其显示结果为:
        45
​
continue、break、exit命令
Linux脚本中的break continue exit return 
​
break
结束并退出本次循环
​
continue 
在循环中不执行continue下面的代码,转而进入下一轮循环
​
exit
退出脚本
常带一个整数给系统,如 exit 0
​
可理解为:break是立马跳出循环;continue是跳出当前条件循环,继续下一轮条件循环;exit是直接退出整个脚本 
例如: 
在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell使用两个命令来实现该功能:break和continue。 
break命令
break命令允许跳出所有循环(终止执行后面的所有循环)。
下面的例子中,脚本进入死循环直至用户输入数字大于5。要跳出这个循环,返回到shell提示符下,需要使用break命令。 
代码如下:
#!/bin/bash
while :
do
        echo -n "请输入1-5之间的数字 " 
        read aNum
        case $aNum in
        1|2|3|4|5) 
                echo "您的数字是 $aNum!"
        ;;
        *) echo "您输入的数字不再1-5中间,游戏结束!"
                        break 
                ;;
        esac 
done
continue命令
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。 
对上面的例子进行修改:
代码如下:
#!/bin/bash
while :
do
        echo -n "请输入1-5之间的数字  " 
        read aNum
        case $aNum in
        1|2|3|4|5) 
                echo "您的数字是 $aNum!"
        ;;
        *) 
                echo "您输入的数字不再1-5中间,游戏结束!";、
                        continue 
                ;;
        esac 
done
​
运行代码发现,当输入大于5的数字时,该例中的循环不会结束.
break和exit的区别
[root@newrain shell]# cat 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,再次尝试
                        esac
        done
esac
done
实战-shell版本jumpserver开发(堡垒机)

ps:整理自己的思路,完善不足的地方

#!/usr/bin/env bash
#
# Author:
#可以先添加上账密验证环节
while :        # 死循环
do
    #trap ':' INT EXIT TSTP TERM HUP  # 拒绝 ctrl+c ctrl+d 其他的退出方式
    clear
cat <<-EOF 
+-------------------------------------+
|        JumpServer @Version1.0       | 
+-------------------------------------+
| a. WebServer Apache.                |
| b. MySQL Databases Server.          |
| c. PHP Development Computer.        |
| d. Quit                             |
+-------------------------------------+
EOF
    read -p "请输入你要登录的服务器编号: "  computer
    case $computer in
    a)
            ssh jumper@192.168.161.129                     # 可以嵌套子case循环
            ;; 
    b)
            ssh jumper@192.168.161.130
            ;; 
    c)
            ssh jumper@192.168.161.131
            ;; 
    d)
            exit
            ;; 
    *)
        printf "ERROR: Please redo your select!"
            ;; 
    esac
done

八、shell 编程-函数

function (功能) 功能函数
​
完成特定功能的代码片段
函数必须先定义才能使用
优点:避免重复的代码
​
定义函数  1 怎么定义 2 定义什么东西
调用函数  1 可以本地调用,也可以调用别的脚本的函数 2 在不调用之前,它相当于没有
取消函数  1 把函数名想象成一个变量名
函数传参  1 跟脚本传参很类似
​
命名空间  1 在shell语言中命名空间函数内和函数外是一致的,函数内外不能赋值同样名字的变量
    local  1 声明一个本地变量(局部变量) 
返回值
    return value 
    value不能超过0-255
shell 函数function

函数声明

function_name () {
   list of commands
}

函数名 function_name,这就是你将使用它从其他地方在你的脚本调用。

取消函数

unset myfunc //取消函数
myfunc()  //函数定义
{
echo “This is my first shell function” 
}
myfunc    //函数调用

产生以下执行结果

./test.sh
This is my first shell function
函数必须提前定义测试
[root@newrain fun]# cat fun05.sh 
#!/bin/bash
fun () {
echo "hello"
}
fun
unset fun
fun
[root@newrain fun]# bash fun05.sh
hello
fun05.sh: line 8: fun: command not found
函数的返回值,返回的是函数体内最后一条命令是否成功的返回值
[root@newrain fun]# systemctl stop httpd 
[root@newrain fun]# cat fun03.sh 
#!/bin/bash
fun() {
        systemctl status httpd &>/dev/null
        systemctl status vsftpd &>/dev/null
}
fun 
echo $?
[root@newrain fun]# systemctl stop vsftpd
[root@newrain fun]# bash fun03.sh 
3

函数传参 在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数

示例

[root@newrain fun]# cat fun06.sh 
#!/bin/bash
fun() {
        echo $[$1*$2*$3]
}
fun 1 2 3
修改版:
[root@newrain fun]# cat fun06.sh 
#!/bin/bash
if [ ! $# -eq 3 ];then
        echo "Must Input Three number: p1 p2 p3"
exit fi
fun() {
        echo $[$1*$2*$3]
}
fun $1 $2 $3

-w 前面会有一个零

001

002

003

004

005

006

如果执行删除,会出现删除失败,因为前面两个零

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值