当前位置:网站首页>Shell(4) Conditional Control Statement
Shell(4) Conditional Control Statement
2022-08-05 04:20:00 【AHui_CSDN】
一. while循环
当前条件表达式成立(为真)则执行do后面的命令
语法结构:
while [ 条件表达式 ]
do
命令的集合
done
案例: 写一个死循环脚本
第一种
[[email protected] ]# cat while.sh
while true
do
echo test
sleep 2
done
第二种
[[email protected] day3]# cat while.sh
while [ 10 -gt 5 ]
do
echo test
sleep 2
done
第三种
[[email protected] day3]# cat while.sh
while [ -f /etc/hosts ]
do
echo test
sleep 2
done
while数字循环
[[email protected] ]# cat while.sh
i=1
while [ $i -le 10 ]
do
echo $i
let i++
done
[[email protected] ]# sh while.sh
1
2
3
4
5
6
7
8
9
10
案例: while从1加到100
[[email protected] ]# cat while.sh
i=1
while [ i − l e 100 ] d o c o u n t = i -le 100 ] do count= i−le100]docount=[count+i]
let i++
done
echo $count
[[email protected] ]# sh while.sh
5050
案例: while读取文件
forThe loop reads the file separated by spaces whileLoops are separated by lines
[[email protected] ]# cat read.sh
#!/bin/bash
while read line
do
echo $line
done</etc/hosts
[[email protected] ]# sh read.sh
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
案例: while创建用户
使用for循环(command line execution)
[[email protected] ]# for i in 取值列表; do 执行的命令;done
[[email protected] ]# for i in `cat user.txt`;do echo $i;done
aa
qq
bb
cc
[[email protected] ]# for i in `cat user.txt`;do useradd $i;done
[[email protected] ]# 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
forLoop delete users
[[email protected] ]# for i in `cat user.txt`;do userdel -r $i;done
使用while循环批量创建用户
[[email protected] ]# cat user.sh
#!/bin/bash
while read line
do
useradd $line
done< user.txt
[[email protected] ]# sh user.sh
[[email protected] ]# 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
Create users in batches by passing user parameters
[[email protected] ]# cat user.sh
#!/bin/bash
read -p "Please enter the user's prefix name: " pre
read -p "Please enter the number of users to create: " 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多级跳
三层循环:
[[email protected] ]# 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跳出循环
[[email protected] ]# 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 Execution continues from the beginning, ignoring the rest of the code
[[email protected] ]# 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 Exit the loop and continue execution
[[email protected] ]# cat user.sh
#!/bin/bash
read -p "Please enter the user's prefix name: " pre
read -p "Please enter the number of users to create: " 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:
[[email protected] ]# cat user.sh
#!/bin/bash
read -p "Please enter the user's prefix name: " pre
read -p "Please enter the number of users to create: " 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
二.函数
函数的特点:
- 先定义在调用 If it is only defined and not called, the script will not execute(Variables are only defined but not called and assignments are performed)
- Functions are commands(代码)的集合(变量只能赋一个值 Functions can be assigned multiple values)
- 可以重复调用
Variable to call the script
[[email protected] ]# cat 1.sh
name=oldboy
[[email protected] ]# cat 2.sh
. /server/scripts//1.sh
read -p "请输入你的年龄: " num
echo 名字: $name 年龄: $num
1.函数的定义
[[email protected] ]# cat fun.sh
#!/bin/bash
fun1(){
echo "第一种书写方式"
}
function fun2 {
echo "第二种书写方式"
}
function fun3(){
echo "第三种书写方式"
}
fun1 # 调用函数 Write the function name directly below the function to call
fun2
fun3
函数复用:
[[email protected] ]# source fun.sh
第一种书写方式
第二种书写方式
第三种书写方式
[[email protected] ]# fun1
第一种书写方式
[[email protected] ]# fun2
第二种书写方式
[[email protected] ]# fun3
第三种书写方式
2.函数的传参
Functions cannot directly receive arguments from scripts
You need to use the parameter passing method of the function to pass parameters
Pass parameters directly after the calling function
[[email protected] ]# cat fun.sh
#!/bin/bash
fun(){
if [ -f $1 ]
then
echo "$1 文件存在"
else
echo "$1 文件不存在"
fi
}
fun /etc/hosts /etc/passwd # Pass parameters directly after the calling function name
[[email protected] ]# sh fun.sh
/etc/hosts 文件存在
[[email protected] ]# sh -x fun.sh
+ fun /etc/hosts /etc/passwd
+ '[' -f /etc/hosts ']'
+ echo '/etc/hosts 文件存在'
/etc/hosts 文件存在
[[email protected] ]# cat fun.sh
#!/bin/bash
fun(){
if [ -f $2 ]
then
echo "$2 文件存在"
else
echo "$2 文件不存在"
fi
}
fun $2 $1
[[email protected] ]# sh fun.sh /etc/hosts /etc/passwd
/etc/hosts 文件存在
3.函数的变量
The current global variable is supported in the function
[[email protected] ]# cat fun.sh
#!/bin/bash
file=/etc/hosts
fun(){
if [ -f $file ]
then
echo "$file 文件存在"
else
echo "$file 文件不存在"
fi
}
fun
[[email protected] ]# cat fun.sh
#!/bin/bash
num=2
fun(){
for i in `seq $num`
do
count=$[$count+$num]
done
echo $count
}
fun
Define the local variables of the function: Only takes effect within the function body
[[email protected] ]# 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返回状态码:
[[email protected] day2]# cat env.sh
#!/bin/sh
read -p "Please Input name env: " name
[ -z $name ] && echo "A name is required" && 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
by assignment:
[[email protected] ]# 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
[[email protected] ]# sh fun.sh /etc/passwd
/etc/passwd 文件存在
[[email protected] ]# sh fun.sh /etc/passwdssss
/etc/passwdssss 文件不存在
案例: 重复判断
# 判断下载YUMA function of whether the warehouse is successful
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=$?
#Call the function name to execute the command in the function body
test_yum
elif [ ${os_vs%%.*} -eq 6 ]
案例: 显示主菜单
[[email protected] ]# cat menu.sh
#!/bin/bash
menu1(){
echo "1.PHP"
echo "2.MySQL"
echo "h.显示主菜单"
}
menu1
while true
do
read -p "Please enter the service tag you want to install: " num
if [ $num = 1 ];then
while true
do
echo "1.PHP1.1"
echo "2.PHP1.2"
echo "3.返回主菜单"
read -p "Please enter the installed version number: " 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)
命令集合
;;
*)
None of the above patterns were matched 则执行 * 下的命令
esac
案例:创建或删除用户
[[email protected] ]# cat case.sh
#!/bin/bash
for i in `seq 10`
do
echo oldboy$i
done
read -p "Choose to delete or create the above user:[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语句
[[email protected] ]# cat case.sh
#!/bin/bash
for i in `seq 10`
do
echo oldboy$i
done
read -p "Choose to delete or create the above user:[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
案例: 查看系统信息
菜单:
- 显示登录信息(执行w)
- 显示内存
- 显示磁盘
- 显示IP地址
- show extranetIP地址
- 显示主机名称
- 显示菜单(You can clear the screen first in the display menu)
通过case语句执行 写入死循环
[[email protected] ]# 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 "Please enter the system information number to view[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
重启 Stop first and then start /usr/sbin/nginx -s stop && /usr/sbin/nginx
重载 /usr/sbin/nginx -s reload
状态 自定义
[[email protected] ]# 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
边栏推荐
- 8.04 Day35-----MVC三层架构
- Spark基础【介绍、入门WordCount案例】
- How to solve the three major problems of bank data collection, data supplementary recording and index management?
- C语言-大白话理解原码,反码和补码
- The first performance test practice, there are "100 million" a little nervous
- 浅析主流跨端技术方案
- Redis key basic commands
- 1007 Climb Stairs (greedy | C thinking)
- 将故事写成我们
- UI自动化测试 App的WebView页面中,当搜索栏无搜索按钮时处理方法
猜你喜欢
多御安全浏览器 V10.8.3.1 版正式发布,优化多项内容
[MRCTF2020]PYWebsite
[SWPU2019]Web1
Develop your own node package
Acid (ACID) Base (BASE) Principles for Database Design
Paparazzi: Surface Editing by way of Multi-View Image Processing
什么是ASEMI光伏二极管,光伏二极管的作用
[极客大挑战 2019]FinalSQL
Analyses the mainstream across technology solutions
请写出SparkSQL语句
随机推荐
Visibility of multi-column attribute column elements: display, visibility, opacity, vertical alignment: vertical-align, z-index The larger it is, the more it will be displayed on the upper layer
In the hot summer, teach you to use Xiaomi smart home accessories + Raspberry Pi 4 to connect to Apple HomeKit
银行数据采集,数据补录与指标管理3大问题如何解决?
Shell(4)条件控制语句
DEJA_VU3D - Cesium功能集 之 059-腾讯地图纠偏
write the story about us
Why did you start preparing for the soft exam just after the PMP exam?
UE4 通过与其它Actor互动开门
No regrets, the appium automation environment is perfectly built
SkiaSharp 之 WPF 自绘 粒子花园(案例版)
UI自动化测试 App的WebView页面中,当搜索栏无搜索按钮时处理方法
pyqt5 + socket 实现客户端A经socket服务器中转后主动向客户端B发送文件
Machine Learning Overview
Analyses the mainstream across technology solutions
商业智能BI业务分析思维:现金流量风控分析(一)营运资金风险
Four-digit display header design
JeeSite新建报表
DEJA_VU3D - Cesium功能集 之 056-智图Arcgis地图纠偏
How to identify false evidence and evidence?
36-Jenkins-Job Migration