SMZ

day04:for、case

假如需要进行批量的操作,例如批量添加用户,批量复制文件。这些批量执行的操作时if语句无法实现的,只能依靠循环语句

再次之前了解一个造数工具:seq

  seq 1 1 10    ###从1开始每次自加1,输出到10结束。即输出1-10

 

for循环语句——基于变量赋值的循环(只要有值赋给变量,就一直循环、直到所有的值赋值完毕,循环结束)

for 变量名 in 取值列表【假如此处定以了多个值,空格分隔每一个值】

do

  语句

done

例如:监测一段ip内的主机,那些在线、不在线(ping通认为在线)

vim /server/scripts/day04.sh 
#!/bin/bash
for i in `seq 1 10`
do
    IP=192.168.31.${i}
    ping -c2 -W1 ${IP} >/dev/null    ##ping对应主机,-c指定包的个数,-W指定超时时间
    if [ $? -eq 0 ]  ##判断ping命令的返回结果是否等于0,ping通返回0,ping不通返回非0
    then
        echo "${IP} is online"
    else
        echo "${IP} is not online"
    fi
done

执行:

[root@rhel4 scripts]# bash day04.sh
192.168.31.1 is online
192.168.31.2 is online
192.168.31.3 is not online
192.168.31.4 is not online
192.168.31.5 is not online
192.168.31.6 is not online
192.168.31.7 is not online
192.168.31.8 is not online
192.168.31.9 is not online
192.168.31.10 is not online

 例如:批量添加用户,并配置初始密码为123456

vim /server/scripts/day04.sh 
#!/bin/bash
for user_name in user1 user2  user3  ##依次把user1、user2、user3赋值给变量user_name
do
    id ${user_name} > /dev/null 2>&1  ##判断本地有该用户,任何输出都不显示,有则返回0;无则返回非0
    if [ $? -eq 0 ]   ##判断上条shell的返回结果
    then
        echo "${user_name} already exists"
    else
        useradd ${user_name} && echo 123456 | passwd --stdin ${user_name} >/dev/null 2>&1   ##添加用户、并且赋予密码
        if [ $? -eq 0 ]  ##判断上条添加用户和修改密码的shel语句是否执成功
        then    ##为真
            echo "${user_name} create successfully..."
        else    ##为假
            echo "${user_name} create failed..."
        fi
    fi
done

执行:

[root@rhel4 ~]# bash /server/scripts/day04.sh    ##第一次执行会添加用户
user1 create successfully...
user2 create successfully...
user3 create successfully...
[root@rhel4 ~]# bash /server/scripts/day04.sh     ##第二次执行,判断系统有该用户,不添加
user1 already exists
user2 already exists
user3 already exists

 

================================

case 语句:  根据变量的不同取值执行不同的操作

      一般与用户交互输入,根据不同的输入,执行不同的操作

      *每个case的匹配模式必须以 )结尾,;; 表示命令序列的结束

case 变量名 in

变量值1)

  命令序列1;;

变量值2)

  命令序列2;;

变量值N)

  命令序列N;;

*)    ##都不匹配,才是匹配上*

  命令序列*;;

例如:

vim /server/scripts/day04.sh 
#!/bin/bash
read -p "请输入'mem|disk|cpu'其中的一个:" info
case $info in
mem)
    free -m;;
disk)
    df -h | grep /$;;    
cpu)
    w | sed -n 1p;;
*)  ##以上都没有匹配上,该条为通用匹配
    echo "输入错误";;
esac

执行:

[root@rhel4 ~]# bash /server/scripts/day04.sh
请输入'mem|disk|cpu'其中的一个:mem
              total        used        free      shared  buff/cache   available
Mem:           1839         102        1579           8         156        1578
Swap:          2047           0        2047
[root@rhel4 ~]# bash /server/scripts/day04.sh
请输入'mem|disk|cpu'其中的一个:disk
/dev/mapper/centos-root   27G  2.0G   25G    8% /
[root@rhel4 ~]# bash /server/scripts/day04.sh
请输入'mem|disk|cpu'其中的一个:cpu
 14:49:56 up  1:41,  2 users,  load average: 0.02, 0.03, 0.05
[root@rhel4 ~]# bash /server/scripts/day04.sh
请输入'mem|disk|cpu'其中的一个:111
输入错误

 

posted on 2019-12-12 14:06  SMZ  阅读(332)  评论(0编辑  收藏  举报

导航