Shell(3)条件控制语句

一.if判断

单分支语句: 一个条件 一个结果

第一种写法: then在表达的后面 加个分号;

if 条件表达式;then
   执行的命令集合
fi

第二种写法: then在if的下面条件表达式的后面不需要加分号;

if 条件表达式
then
    执行命令
fi

案例:

if [ 20 -eq 20 ]
then 
    echo ok
fi
if [ -f /etc/hosts ];then
   echo 文件存在
fi
if [[ root =~ ^r ]]
then 
    echo ok
fi

if的单分支和&& 相同
一个条件 一个结果

[root@test]# [ 10 -eq 10 ] && echo ok
ok
[root@test ]# [ 10 -eq 11 ] && echo ok

[root@test ]# cat if.sh
if [ 10 -eq 10 ]
then
    echo ok
fi


单条件
if  [ 你有房 ]
then
    我就嫁给你
fi 

双分支 一个条件 两个结果
if [ 你有房 ]
then 
    我就嫁给你
else
    拜拜
fi

[ 10 -eq 10 ] && echo 成立 || echo 不成立 

多分支 多个条件 多个结果

if [ 你有房 ]
then 
    我就嫁给你 
elif [ 你有钱 ]
then
    我也嫁给你
elif [ 你活好 ] Linux学的好
then
    先处对象
else
    拜拜
fi

案例: 根据不同的操作系统版本安装不同的YUM源

  1. 获取操作系统版本号
  2. 通过表达判断
  3. 部署YUM仓库

框架:

[root@test ]# cat if.sh
#!/bin/bash
#获取操作系统版本号
os_vs=`awk '{print $(NF-1)}' /etc/redhat-release`
if [ ${os_vs%%.*} -eq 7 ]
then
    # 备份默认YUM仓库
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
    # 下载新的YUM仓库
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
elif [ ${os_vs%%.*} -eq 6 ]
then
    # 备份默认YUM仓库
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
    # 下载新的YUM仓库
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-6.10.repo
elif [ ${os_vs%%.*} -eq 8 ]
then
    # 备份默认YUM仓库
    mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
    # 下载新的YUM仓库 
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
fi

完善脚本:

[root@test ]# cat if.sh 
#!/bin/bash
#获取操作系统版本号
# 调用系统函数库
[ -f /etc/init.d/functions ] && . /etc/init.d/functions

os_vs=`awk '{print $(NF-1)}' /etc/redhat-release`
backup_yum='mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup'

# 判断网络
ping -c1 -W1 www.baidu.com &>/dev/null
if [ $? -ne 0 ]
then
    systemctl restart network
    if [ $? -eq 0 ];then
        action "重启网卡成功" /bin/true
    else
        action "网卡重启失败请手动检查配置" /bin/false
    fi
    ping -c1 -W1 www.baidu.com &>/dev/null
    [ $? -ne 0 ] && action "请管理手动检查网络" /bin/false
fi

# 判断wget是否存在 不存在则安装
which wget &>/dev/null
if [ $? -ne 0 ]
then
    echo "正在安装wget请稍等........"
    yum -y install wget &>/dev/null
    if [ $? -eq 0 ];then
    action "wget install is " /bin/true
    else
    action "wget install is" /bin/false
    echo "正在安装wget安装成功继续执行脚本.."
    fi
fi

if [ ${os_vs%%.*} -eq 7 ]
then
    # 备份默认YUM仓库
    $backup_yum
    # 下载新的YUM仓库
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo &>/dev/null
    if [ $? -eq 0 ];then
    action "yum仓库安装" /bin/true
    else
    action "yum仓库安装" /bin/false
    fi

elif [ ${os_vs%%.*} -eq 6 ]
then
    # 备份默认YUM仓库
    $backup_yum
    # 下载新的YUM仓库
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-6.10.repo
elif [ ${os_vs%%.*} -eq 8 ]
then
    # 备份默认YUM仓库
    $backup_yum
    # 下载新的YUM仓库 
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
fi

案例: 输入两个整数判断比较两个数大小

[root@test ]# cat num.sh 
#!/bin/sh
read -p "Please Input two Number: " num1 num2
if [[ ! $num1 =~ ^[0-9]+$ || ! $num2 =~ ^[0-9]+$ ]];then
   echo "请输入整数"
   exit
fi
if [ $num1 -gt $num2 ]
then
    echo "$num1 > $num2"
elif [ $num1 -lt $num2 ]
then
    echo "$num1 < $num2"
else
    echo "$num1 = $num2"
fi

案例: if菜单

打印输出菜单 安装多个不同的版本

[root@test ]# cat server.sh 
#!/bin/sh
echo -e "\t\t\t\t\t \033[40;32m 1.PHP \033[0m"
echo -e "\t\t\t\t\t \033[40;32m 2.Redis \033[0m"
echo -e "\t\t\t\t\t \033[40;32m 3.MySQL \033[0m"
echo -e "\t\t\t\t\t \033[40;32m 4.Nginx \033[0m"
cat<<EOF
		 1.PHP
		 2.Redis
		 3.MySQL
		 4.Nginx
EOF

二级菜单:

[root@test ]# cat server.sh 
#!/bin/sh
echo -e "\t\t\t\t\t \033[40;32m 1.PHP \033[0m"
echo -e "\t\t\t\t\t \033[40;32m 2.Redis \033[0m"
echo -e "\t\t\t\t\t \033[40;32m 3.MySQL \033[0m"
echo -e "\t\t\t\t\t \033[40;32m 4.Nginx \033[0m"
read -p "请输入你要安装的服务名称或者编号:[1|PHP|2|Redis|3|MySQL|4|Nginx] " num
if [ $num = 1 -o $num = PHP ]
then
        echo -e "\t\t\t\t\t \033[40;34m 1.PHP5.4 \033[0m"
	echo -e "\t\t\t\t\t \033[40;34m 2.PHP7.1 \033[0m"
	echo -e "\t\t\t\t\t \033[40;34m 3.PHP7.2 \033[0m"
	echo -e "\t\t\t\t\t \033[40;34m 4.PHP7.4 \033[0m"
        read -p "请选择你要安装的版本号:[1|2|3]" num
        if [ $num -eq 1 ];then
           echo "yum_install_php5.4............."
        elif [ $num -eq 2 ];then
           echo "yum_install_php7.1............."
	else
	   echo "请按照菜单选择别瞎选!!!"
   	   exit
	fi

elif [ $num = 2 -o $num = Redis ]
then
        echo -e "\t\t\t\t\t \033[40;33m 1.Redis-1.6 \033[0m"
        echo -e "\t\t\t\t\t \033[40;33m 2.Redis-1.7 \033[0m"
        echo -e "\t\t\t\t\t \033[40;33m 3.Redis-1.8 \033[0m"
        echo -e "\t\t\t\t\t \033[40;33m 4.Redis-1.9 \033[0m"
                read -p "请选择你要安装的版本号:[1|2|3]" num
        if [ $num -eq 1 ];then
           echo "yum_install_redis1.6............."
        elif [ $num -eq 2 ];then
           echo "yum_install_redis1.7............."
        fi
else
   echo "请按照菜单选择别瞎选!!!"
   exit

fi

完善脚本:

[root@test ]# cat server.sh
#!/bin/sh
while true
do
	echo -e "\t\t\t\t\t \033[40;32m 1.PHP \033[0m"
	echo -e "\t\t\t\t\t \033[40;32m 2.Redis \033[0m"
	echo -e "\t\t\t\t\t \033[40;32m 3.MySQL \033[0m"
	echo -e "\t\t\t\t\t \033[40;32m 4.Nginx \033[0m"
	echo -e "\t\t\t\t\t \033[40;32m 5.退出脚本 \033[0m"
	read -p "请输入你要安装的服务名称或者编号:[1|PHP|2|Redis|3|MySQL|4|Nginx] " num
	if [ $num = 1 -o $num = PHP ]
	then
	    while true
 	    do
		echo -e "\t\t\t\t\t \033[40;34m 1.PHP5.4 \033[0m"
		echo -e "\t\t\t\t\t \033[40;34m 2.PHP7.1 \033[0m"
		echo -e "\t\t\t\t\t \033[40;34m 3.PHP7.2 \033[0m"
		echo -e "\t\t\t\t\t \033[40;34m 4.PHP7.4 \033[0m"
		echo -e "\t\t\t\t\t \033[40;34m 5.返回主菜单 \033[0m"
		read -p "请选择你要安装的版本号:[1|2|3]" num
		if [ $num -eq 1 ];then
		   echo "yum_install_php5.4............."
		elif [ $num -eq 2 ];then
		   echo "yum_install_php7.1............."
		elif [ $num -eq 5 ];then
		      break
		else
		   echo "请按照菜单选择别瞎选!!!"
		   exit
		fi
	     done
	elif [ $num = 2 -o $num = Redis ]
	then
		echo -e "\t\t\t\t\t \033[40;33m 1.Redis-1.6 \033[0m"
		echo -e "\t\t\t\t\t \033[40;33m 2.Redis-1.7 \033[0m"
		echo -e "\t\t\t\t\t \033[40;33m 3.Redis-1.8 \033[0m"
		echo -e "\t\t\t\t\t \033[40;33m 4.Redis-1.9 \033[0m"
			read -p "请选择你要安装的版本号:[1|2|3]" num
		if [ $num -eq 1 ];then
		   echo "yum_install_redis1.6............."
		elif [ $num -eq 2 ];then
		   echo "yum_install_redis1.7............."
		fi
	elif [ $num = 5 ]
        then
	     exit
	else
	   echo "请按照菜单选择别瞎选!!!"
	   echo "请重新输入编号"

        fi
done

案例: 猜数字游戏

1.生成一个随机数
2.让用户输入数字
3.猜大小 大了提示大了 小则提示小了 输入正确则提示恭喜猜对了

$RANDOM 数字范围: 0-32767

echo $((RANDOM%100+1)) 1-100的数字

[root@test ]# cat ran.sh 
#!/bin/bash
ran=`echo $((RANDOM%100+1))`

while true
do
	let i++
	read -p "请你输入要猜的数字[1-100]: " num
	if [ $num -gt $ran ]
	then
	   echo "你输入数字的大了"
	elif [ $num -lt $ran ]
	then
	   echo "你输入数字的小了"
	else
	     echo "恭喜你猜对了中奖号码是: $ran"
	     echo "总共猜了$i 次"
	     exit
	fi
done

案例:系统自动猜 并且统计猜的数字

系统猜过的数字放入一个文本
然后过滤统计判断 如果有则重复赋值
(重复赋值)

[root@test ]# cat test.sh
#!/bin/bash
> 1.txt
num=`echo $((RANDOM%100+1))`
while true
do
            while true
	    do
		ran=`echo $((RANDOM%100+1))`
		if [ `grep -w $ran 1.txt|wc -l` -eq 1  ];then
	            continue
	        else
	           let i++
		   echo $ran >> 1.txt
		   break
	        fi
	    done
	    if [ $num -eq $ran ];then
	       echo "恭喜系统猜对了$i 次"
	       exit
	    fi

done

案例:双色球

6红+1个篮球 共7个号码
6红数字范围: 1-33
1个篮球: 1-16
当前1-33里的数字被赋值 不能在给其他变量赋值

#!/bin/bash
> 1.txt
> red.txt
   while true
   do
	   ran=`echo $((RANDOM%33+1))`
	   if [ `grep -w $ran 1.txt|wc -l` -eq 1 ];then
	      continue
	   else
	      let i++
 	      if [ $i -eq 7 ];then
 	               echo "红色球号码出球完毕! 等待篮色球出球"
		       sleep 2
	                num=`echo $((RANDOM%16))`
		       echo  -e "蓝色球号码为: \033[40;34m $num \033[0m"|tee blue.txt
		       break
	      fi
  	      echo $ran >> 1.txt
	      sleep 2
	      echo -e "第 $i 个双色球红球号码为: \033[40;31m $ran \033[0m"|tee -a red.txt
	   fi
   done
sleep 3
echo -e "本期双色球出球结果为: 红球 \033[40;31m  `cat red.txt |awk '{print $5}'|sort -n|xargs -n6` \033[0m  篮球: \033[40;34m $num \033[0m"

二.for循环

语法结构:
	for 变量名称 in  取值列表
	do
	    动作
	done

案例:取值列表:

数字 字符串 命令 序列 以空格为分隔符

循环数字:

[root@test ]# cat for.sh
#!/bin/bash
for i in 1 2 3 4 5
do
	echo $i
done
[root@test ]# sh for.sh
1
2
3
4
5

循环字符串

[root@test ]# cat for.sh
#!/bin/bash
for i in ahui test1 b13k
do
	echo $i
done
[root@test ]# sh for.sh
ahui
test1
b13k

值的列表可以使用双引号引用

[root@test ]# cat for.sh
#!/bin/bash
for i in "ahui test1" b13k
do
	echo $i
done
[root@test ]# sh for.sh
ahui test1
b13k

注意: 输出的结果可以和for循环的列表没有任何关系 和循环次数有关 赋值几次则动作执行几次

[root@test ]# cat for.sh
#!/bin/bash
for i in a b c
do
	echo ok
done
[root@test ]# sh for.sh
ok
ok
ok

统计循环或者赋值次数

[root@test ]# cat for.sh
#!/bin/bash
for i in a b c
do
	let a++
done
echo $a
[root@test ]# sh for.sh
3

案例:for循环读取文件

[root@test ]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@test ]# cat for.sh 
#!/bin/bash
for i in `cat /etc/hosts`
do
	echo $i
done
[root@test ]# sh for.sh 
127.0.0.1
localhost
localhost.localdomain
localhost4
localhost4.localdomain4
::1
localhost
localhost.localdomain
localhost6
localhost6.localdomain6

for循环支持序列

支持字符

[root@test ]# cat for.sh
#!/bin/bash
for i in {a..c}
do
	echo $i
done
[root@test ]# sh for.sh
a
b
c

支持数字

[root@test ]# cat for.sh
#!/bin/bash
for i in {1..10}
do
	echo $i
done
[root@test ]# sh for.sh
1
2
3
4
5
6
7
8
9
10

支持命令

[root@test ]# cat for.sh
#!/bin/bash
for i in `seq 10`
do
	echo $i
done

案例1: 测试一个网段内的IP地址是否在线

ping通则为在线

   [root@test ]# cat for.sh 
	#!/bin/bash
	for i in {1..10}
	do
	   {
		ip=10.0.0.$i
		ping -c1 -W1 $ip &>/dev/null
		if [ $? -eq 0 ]
		then
			echo "$ip 在线"
		fi
		} &
	done
	wait   # 等待后台程序执行完毕后继续往下执行
	echo done..................

案例2: 批量创建用户 每个用户8位随机密码 并且保存用户名对应密码关系表

要求用户输入前缀 用户输入个数test01…test10

[root@test ]# cat user.sh 
#!/bin/bash
read -p "请输入用户名称的前缀: " prefix
read -p "请输入要创建用户的个数: " num
for i in `seq $num`
do
	echo ${prefix}$i
done
read -p "删除还是创建以上用户[y|n]" re
if [ $re = y ]
then
	for a in `seq $num`
	do
	   user=${prefix}$a
	   id $user &>/dev/null
	   if [ $? -ne 0 ];then
		  useradd $user
		  if [ $? -eq 0 ];then
		 echo "$user 创建成功"
	  fi
	   else
		  echo "useradd: user $user 已存在"
	   fi
	done  
elif [ $re = n ]
then
   for b  in `seq $num`
   do
	   user=${prefix}$b
	   id $user &>/dev/null
	   if [ $? -eq 0 ];then
		  userdel -r $user
		  [ $? -eq 0 ] && echo "$user 删除成功"
	   else
		  echo "$user 不存在"
	   fi
   done
fi

案例3: for循环从1加到100 笔试题

[root@test ]# cat for1.sh 
#!/bin/bash
for i in {1..100}
do
     count=$[$count+$i]
done
echo $count
[root@test ]# cat for1.sh
#!/bin/bash
for i in {1..100}
do
     count=$[count+i]		# 此处括号中可以不加$
done
echo $count

[root@test ]# seq -s + 100|bc
5050

案例4:反向破解随机数的MD5值

[root@test ]# cat for2.sh 
num1=31d30eea8d0968d6458e0ad0027c9f80
for i in `seq 15`
do
         ran=`echo ${i}|md5sum|awk '{print $1}'`
         if [ $num1 = $ran ]
         then
             echo "$i $ran"
	 fi
done
[root@test ]# sh for2.sh
10 31d30eea8d0968d6458e0ad0027c9f80
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值