Shell(4)条件控制语句

本文详细介绍了Shell脚本中的while循环、for循环及其多种使用案例,包括死循环、数字循环、读取文件、创建用户等。同时讲解了函数的定义、调用、参数传递、变量及返回值,以及case语句的运用,展示了在用户管理、系统信息查看和Nginx服务控制等场景的应用。
摘要由CSDN通过智能技术生成

一. while循环

当前条件表达式成立(为真)则执行do后面的命令

语法结构:
while [ 条件表达式 ]
do
     命令的集合
done 

案例: 写一个死循环脚本

第一种

[root@test ]# cat while.sh 
while true
do
	  echo test
	  sleep 2
done

第二种

[root@test day3]# cat while.sh 
while [ 10 -gt 5 ]
do
	  echo test
	  sleep 2
done

第三种

[root@test day3]# cat while.sh
while [ -f /etc/hosts ]
do
	  echo test
	  sleep 2
done

while数字循环

[root@test ]# cat while.sh
i=1
while [ $i -le 10 ]
do
	  echo $i
	  let i++
done
[root@test ]# sh while.sh
1
2
3
4
5
6
7
8
9
10

案例: while从1加到100

[root@test ]# cat while.sh
i=1
while [ i − l e 100 ] d o c o u n t = i -le 100 ] do count= ile100]docount=[count+i]
let i++
done
echo $count
[root@test ]# sh while.sh
5050

案例: while读取文件

for循环读取文件按照空格分割 while循环按照行分隔

[root@test ]# cat read.sh
#!/bin/bash
while read line
do
	 echo $line
done</etc/hosts
[root@test ]# sh read.sh
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

案例: while创建用户

使用for循环(命令行行执行)

[root@test ]# for i in 取值列表; do 执行的命令;done
[root@test ]# for i in `cat user.txt`;do echo $i;done
aa
qq
bb
cc

[root@test ]# for i in `cat user.txt`;do useradd $i;done
[root@test ]# tail -4 /etc/passwd
aa:x:1000:1000::/home/aa:/bin/bash
qq:x:1001:1001::/home/qq:/bin/bash
bb:x:1002:1002::/home/bb:/bin/bash
cc:x:1003:1003::/home/cc:/bin/bash

for循环删除用户

[root@test ]# for i in `cat user.txt`;do userdel -r $i;done

使用while循环批量创建用户

[root@test ]# cat user.sh
#!/bin/bash
while read line
do
	  useradd $line
done< user.txt
[root@test ]# sh user.sh
[root@test ]# tail -4 /etc/passwd
aa:x:1000:1000::/home/aa:/bin/bash
qq:x:1001:1001::/home/qq:/bin/bash
bb:x:1002:1002::/home/bb:/bin/bash
cc:x:1003:1003::/home/cc:/bin/bash

通过用户传参的方式批量创建用户

[root@test ]# cat user.sh
#!/bin/bash
read -p "请输入用户的前缀名称: " pre 
read -p "请输入创建用户的个数: " num
i=1
while [ $i -le $num ] 
do
      user=${pre}$i
      id $user &>/dev/null
	  re=$?
      if [ $re -ne 0 ];then
         useradd $user
         [ $? -eq 0 ] && echo "$user 创建成功"
	  elif [ $re -eq 0 ]
	     echo "$user 已经存在"
      fi  
      let i++
done

while多级跳

三层循环:

[root@test ]# cat while1.sh 
#!/bin/bash
while true
do
         echo "第一级"
         sleep 1
         while true
	 do
	     echo "第二级"
	     sleep 1

	     while true
	     do
	       echo "第三级"
	       sleep 1
	     done

	 done
done
echo done....................

break跳出循环

[root@test ]# cat while1.sh 
#!/bin/bash
while true
do
         echo "第一级"
         sleep 1
         while true
	 do
	     echo "第二级"
	     sleep 1

	     while true
	     do
	       echo "第三级"
	       sleep 1
	       break 3
	     done

	 done
done
echo done....................

exit 退出整个脚本

continue 忽略剩余代码从头继续执行

[root@test ]# cat while1.sh 
#!/bin/bash
while true
do
		 echo "第一级"
		 sleep 1
		 while true
	 do
		 echo "第二级"
		 sleep 1
		 continue
		 while true
		 do
		   echo "第三级"
		   sleep 1
		 done

	 done
done
echo done....................

break 跳出循环体继续执行

[root@test ]# cat user.sh
#!/bin/bash
read -p "请输入用户的前缀名称: " pre 
read -p "请输入创建用户的个数: " num
i=1
while [ $i -le $num ] 
do
	  user=${pre}$i
	  id $user &>/dev/null
	  if [ $? -ne 0 ];then
		 useradd $user
		 [ $? -eq 0 ] && echo "$user 创建成功"
	  else
	 break
	  fi  
	  let i++
done
echo done..............

continue:

[root@test ]# cat user.sh 
#!/bin/bash
read -p "请输入用户的前缀名称: " pre 
read -p "请输入创建用户的个数: " num
i=0
while [ $i -le $num ] 
do
	  let i++
	  user=${pre}$i
	  id $user &>/dev/null
	  if [ $? -ne 0 ];then
		 useradd $user
		 [ $? -eq 0 ] && echo "$user 创建成功"
	  else
	      continue
	  fi  
done
echo done..............

#!/bin/bash
>test.txt
while true
do
	  ran=`echo $((RANDOM%100+1))`
	  if [ `grep -w $ran test.txt|wc -l` -eq 1 ];then
		 continue
	  fi
	  echo $ran >> test.txt
done

二.函数

函数的特点:

  1. 先定义在调用 如果只定义不调用则脚本不会执行(变量只定义不调用也会执行赋值)
  2. 函数为命令(代码)的集合(变量只能赋一个值 函数可以赋多个值)
  3. 可以重复调用

调用脚本的变量

[root@test ]# cat 1.sh 
name=oldboy
[root@test ]# cat 2.sh 
. /server/scripts//1.sh
read -p "请输入你的年龄: " num
echo 名字: $name 年龄: $num

1.函数的定义

[root@test ]# cat fun.sh 
#!/bin/bash
fun1(){
     echo "第一种书写方式"
}
function fun2 {
     echo "第二种书写方式"
}
function fun3(){
     echo "第三种书写方式"
}
fun1			# 调用函数 直接在函数的下面写函数名称即可调用
fun2
fun3

函数复用:

[root@test ]# source fun.sh 
第一种书写方式
第二种书写方式
第三种书写方式
[root@test ]# fun1
第一种书写方式
[root@test ]# fun2
第二种书写方式
[root@test ]# fun3
第三种书写方式

2.函数的传参

函数无法直接接收脚本的传参
需要使用函数的传参方式进行传参
直接在调用函数的后面进行传参

[root@test ]# cat fun.sh
#!/bin/bash
fun(){
	 if [ -f $1 ]
	 then
	 echo "$1 文件存在"
	 else
	 echo "$1 文件不存在"
	 fi
}
fun /etc/hosts /etc/passwd		# 在调用函数名称后面直接传参

[root@test ]# sh fun.sh
/etc/hosts 文件存在
[root@test ]# sh -x fun.sh 
+ fun /etc/hosts /etc/passwd
+ '[' -f /etc/hosts ']'
+ echo '/etc/hosts 文件存在'
/etc/hosts 文件存在


[root@test ]# cat fun.sh
#!/bin/bash
fun(){
	 if [ -f $2 ]
	 then
	 echo "$2 文件存在"
	 else
	 echo "$2 文件不存在"
	 fi
}
fun $2 $1
[root@test ]# sh fun.sh /etc/hosts /etc/passwd
/etc/hosts 文件存在

3.函数的变量

函数中支持当前的全局变量

[root@test ]# cat fun.sh 
#!/bin/bash
file=/etc/hosts
fun(){
	 if [ -f $file ]
	 then
	 echo "$file 文件存在"
	 else
	 echo "$file 文件不存在"
	 fi
}
fun


[root@test ]# cat fun.sh 
#!/bin/bash
num=2
fun(){
	 for i in `seq $num`
	 do
	 count=$[$count+$num]
	 done 
	 echo $count
}
fun

定义函数的本地变量: 只在函数体内生效

[root@test ]# cat fun.sh 
#!/bin/bash
fun(){
	 local num=20
	 for i in `seq $num`
	 do
	 count=$[$1+$num]
	 done 
	 echo $count
}
fun 10
echo $num

4.函数的返回值

通过exit返回状态码:

[root@test day2]# cat env.sh 
#!/bin/sh
read -p "Please Input name env: " name
[ -z $name ] && echo "必须输入名称" && exit
if [[  $name =~ ^[a-Z]+$ ]];then
   echo $name
else
   exit 100
fi


read -p "Please Input age env: " age
if [[ $age =~ ^[0-9]{2}$ ]];then
  echo $age
else
   exit 200
fi
echo $name $age

通过赋值方式:

[root@test ]# cat fun.sh
#!/bin/bash
fun(){
	 if [ -f $1 ]
	 then
		 return 50
	 else
		 return 100
	 fi
}
fun $1
re=$?
if [ $re -eq 50 ]
then
	 echo "$1 文件存在"
elif  [ $re -eq 100 ]
then
	 echo "$1 文件不存在"
fi
[root@test ]# sh fun.sh /etc/passwd
/etc/passwd 文件存在
[root@test ]# sh fun.sh /etc/passwdssss
/etc/passwdssss 文件不存在

案例: 重复判断

# 判断下载YUM仓库是否成功的函数
test_yum(){
    if [ $re -eq 0 ];then
    action "yum仓库安装" /bin/true
    else
    action "yum仓库安装" /bin/false
    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
	#将执行的返回结果赋值给re
    re=$?
	#调用函数名称执行函数体中的命令
    test_yum

elif [ ${os_vs%%.*} -eq 6 ]

案例: 显示主菜单

[root@test ]# cat menu.sh 
#!/bin/bash
menu1(){
       echo "1.PHP"
   	   echo "2.MySQL"
   	   echo "h.显示主菜单"
}
menu1
while true
do
	   read -p "请输入你要安装的服务编号: " num
           if [ $num = 1 ];then
              while true
	      do
	          echo "1.PHP1.1"
	          echo "2.PHP1.2"
	          echo "3.返回主菜单"
	          read -p "请输入安装的版本号: " re
  		  if [ $re -eq 1  ];then
	   	     echo yum php1.1.....
		  elif [ $re -eq 3 ];then
	 	      break
		  fi
 	      done
 	   elif [ $num = 2 ];then
	      echo "1.MySQL1.1"
	      echo "2.MySQL1.2"
	   elif [ $num = h  ];then
 	      menu1
  	   fi
done

三. case

语法结构:
变量: 直接取值 read读入 赋值
case 变量 in
		  匹配模式1)
			  命令集合
		  ;;
		  匹配模式2)
			  命令集合
		  ;;
		  匹配模式3)
			  命令集合
		  ;;
		  *)
			  没有匹配到上面的模式 则执行 * 下的命令
esac

案例:创建或删除用户

[root@test ]# cat case.sh 
#!/bin/bash
for i in `seq 10`
do
   echo oldboy$i
done
read -p "选择删除或者创建以上用户:[y创建|d删除] " num

case $num in
	y)
	    for a in `seq 10`
	    do
	           user=oldboy$a
	           id $user &>/dev/null
		   if [ $? -eq 0 ];then
	 	      echo $user 用户存在
		   else
		      useradd $user
		      [ $? -eq 0 ] && echo $user 创建成功
		   fi

	    done
	;;
	d)
	    for a in `seq 10`
            do
                   user=oldboy$a
                   id $user &>/dev/null
                   if [ $? -eq 0 ];then
                      userdel -r $user
		      [ $? -eq 0 ] && echo $user 删除成功
                   else
                      echo "$user 用户不存在"
                   fi

            done

        ;;
        *)
	     echo "Usage: $0 [y|yes|d|del]"
esac

for循环包含case语句

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

read -p "选择删除或者创建以上用户:[y创建|d删除] " num

for a in `seq 10`
do
	case $num in
		y)
		  user=oldboy$a
		  id $user &>/dev/null
		   if [ $? -eq 0 ];then
		      echo $user 用户存在
		   else
		      useradd $user
		      [ $? -eq 0 ] && echo $user 创建成功
		   fi

		;;
		d)
			   user=oldboy$a
			   id $user &>/dev/null
			   if [ $? -eq 0 ];then
			      userdel -r $user
			      [ $? -eq 0 ] && echo $user 删除成功
			   else
			      echo "$user 用户不存在"
			   fi

		;;
		*)
		     echo "Usage: $0 [y|yes|d|del]"
	esac
done

案例: 查看系统信息

菜单:

  1. 显示登录信息(执行w)
  2. 显示内存
  3. 显示磁盘
  4. 显示IP地址
  5. 显示外网IP地址
  6. 显示主机名称
  7. 显示菜单(可以先清屏在显示菜单)

通过case语句执行 写入死循环

[root@test ]# cat os.sh 
#!/bin/bash
menu(){
	echo -e "\t\t\t\t\t\t1.f查看内存"
	echo -e "\t\t\t\t\t\t2.d查看磁盘"
	echo -e "\t\t\t\t\t\t3.u查看负载"
	echo -e "\t\t\t\t\t\t4.l查看登录信息"
	echo -e "\t\t\t\t\t\t5.c查看外网IP地址"
	echo -e "\t\t\t\t\t\t6.m显示菜单"
	echo -e "\t\t\t\t\t\t7.q退出脚本"
}
menu
while true
do
	read -p "请输入要查看的系统信息编号[1|f]: " num
	case $num in
		  1|f)
		   free -h
		  ;;
		  2|d)
		   df -h
		 ;;
		  3|u)
		   uptime
		  ;;
		  4|l)
		   w
		 ;;
		  5|c)
		   curl cip.cc
		  ;;
		 6|m)
		    clear
		    menu
		  ;;
		 7|q)
	  	    exit
		  ;;
		  *)
		   echo "Usage: $0 [1|2|3|4|5|6]"
	esac
done

案例: Nginx启动脚本

启动 /usr/sbin/nginx
停止 /usr/sbin/nginx -s stop
重启 先停止后启动 /usr/sbin/nginx -s stop && /usr/sbin/nginx
重载 /usr/sbin/nginx -s reload
状态 自定义

[root@test ]# cat nginx.sh 
#!/bin/bash
. /etc/init.d/functions
re=$1
fun(){
              if [ $? -eq 0 ];then
              action "Nginx $re is " /bin/true
              else
              action "Nginx $re is " /bin/false
              fi
}
case $1 in
	 start)
	      /usr/sbin/nginx
 	      fun
	 ;;
	 stop)
	      /usr/sbin/nginx -s stop
 	      fun
	 ;;
	 restart)
	      /usr/sbin/nginx -s stop
	      sleep 1
	      /usr/sbin/nginx
 	      fun
 	 ;;
	 reload)
	      /usr/sbin/nginx -s reload
 	      fun
	 ;;
	 status)
	      num=`ps axu|grep nginx|grep master|wc -l`
  	      if [ $num -eq 1 ];then
	         action "Nginx is running...."   /bin/true
	      else
	         action "Nginx is down......."   /bin/false
	      fi
 	 ;;
	 *)
	  echo "Usage: $0 [start|stop|restart|reload|status]"
esac
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值