当前位置:网站首页>Shell script integer value comparison, logic test, if statement, extract performance monitoring indicators
Shell script integer value comparison, logic test, if statement, extract performance monitoring indicators
2022-07-19 02:47:00 【For whom do the stars change】
1、 Conditional test operation
[ Conditional expression ]
(1) File test
[ The operator File or directory ]
-d: Test whether it's a directory (Directory)
-e: Test whether the directory or file exists (Exist)
-f: Whether the test is a file ((File)
-r: Test whether the current user has permission to read (Read),
-w: Test whether the current user has permission to write (Write)
-x: Test if executable (Excute ) jurisdiction .
Test directory /media Whether there is ,$? The return value is 0, Indicates that this directory exists
[ -d /media/ ]
echo $?
ls -ld /media/If $? Return value not 0, Indicates that this directory does not exist
[ -d /media/cdrom ]
echo $?
ls -ld /media/cdrom
Test whether the directory exists , The output result is more intuitive “yes” Indicates that the directory exists
[ -d /media/ ] && echo "yes"
nothing “yes” The output indicates that the directory does not exist
[ -d /media/cdrom ] && echo "yes" (2)、 Integer comparison
According to the given two integer values , Judge the relationship between the first number and the second number
[ Integers 1 The operator Integers 2 ]
-eq: The first number equals ((Equal) The second number .
-ne: The first number is not equal to (Not Equal) The second number .
-gt: The first number is greater than (Greater Than) The second number .
-It: The first number is less than (Lesser Than) The second number .
-le: The first number is less than or equal to (Lesser or Equal) The second number .
-ge: The first number is greater than or equal to (Greater or Equal) The second number .
Judge the number of currently logged in users , When more than 5 Hour output “too many”
who |wc -l
unum=`who | wc -l`
[ $unum -gt 5 ] && echo "too many"Determine the currently available free memory (buffers/cache) size , When it is lower than 2048MB Output specific values
Freecc=$(free -m | grep "Mem:" |awk '{print $6}')
[ $Freecc -lt 1024 ] && echo ${Freecc}MB
(3) String comparison
String comparisons are often used to check user input 、 Whether the system environment meets the conditions
[ character string 1 The operator character string 2 ]
=: The first string is the same as the second string .
!=: The first string is not the same as the second string . among ‘!“ The sign means reverse .
-z: Check if the string is empty (Zero Variables that are not defined or assigned null values will be treated as empty strings .
User input “yes” or “no” To confirm a task
read -p "shi fou fu gai xian you wen jian (yes/no)?" ACK yes
[ $ACK = "yes" ] && echo "fu gai"
read -p "shi fou fu gai xian you wen jian (yes/no)?" ACK no
[ $ACK = "no" ] && echo "bu fu gai" (4) Logic test
Logical testing refers to judging the dependency between two or more conditions
command 1 The operator command 2
&&: and
||: perhaps
!: Logical not , Take the opposite
Judge the present linux Whether the kernel version of the system is greater than 2.4.
View kernel
uname -rJudge
A=$(uname -r | awk -F. '{print $1}')
B=$(uname -r | awk -F. '{print $2}')
[ $A -ge 3 ] && [ $B -gt 4 ] && echo "fu he yaoqiu"
2、IF Structure of statement
(1) Single branch if
Only in ‘ Conditions established “ The corresponding code will be executed , Otherwise, nothing will be done .
Grammar format :
if Conditional test operation
then
Command sequence
fi
Determine the mount point directory , If it doesn't exist, it will be created automatically
vim cdrom.sh
#!/bin/bash
MOUNT_DIR="/media/cdrom/"
if [ ! -d $MOUNT_DIR ]
then
mkdir -p $MOUNT_DIR
fi
chmod +x cdrom.sh
./cdrom.shJudge whether the current user is root, If not, report an error and execute “exit 1” Exit script , No more code to execute
vim /opt/root.sh
#!/bin/bash
if [ "$USER" !="root" ]
then
echo " error : Not root user , Insufficient authority !"
exit 1
fi
fdisk -l /dev/sda
su lisi
exit
chmod +x /opt/root.sh
Switch user execution su - user name /opt/root.sh
Switch again root User authentication
(2) Double branch if sentence
Ask for ‘ Conditions established “‘ Conditions not established ” In both cases, different operations are performed .
Grammar format :
if Conditional test operation
then
Command sequence 1
else
Command sequence 2
fi
Determine whether the target host is alive or not , Show test results
vim ping.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is up."
else
echo "Host $1 is down."
fi
ifconfig ens33 192.168.1.10 ( Temporary modification IP Address )
chmod +x ping.sh
./ping.sh 192.168.1.10 (ping Their own IP Address )Show is up. It means success
Check vsftpd Whether the service is running , If running, list the listening address ,PID Number ; Otherwise output the prompt “ Warning ,vsftpd Service not available ”.( Insert linux System installation CD , Install it. vsftpd software package )
vim vsftpd.sh
#!/bin/bash
systemctl status vsftpd &> /dev/null
if [ $? -eq 0 ]
then
echo " Monitor address :$(netstat -anpt | grep vsftpd | awk '{print $4}')"
echo " process PID Number :$(pgrep -x vsftpd)"
else
echo " Warning :vsftpd Service not available !"
fi
chmod +x vsftpd.sh
./vsftpd.sh Display when not started : Warning vsftpd If the service is unavailable, it will succeed
Display at startup : Listening port ::::21, process PID Number :61072 The successful
(3) Multiple branches if sentence
because if The statement can be established according to the test results 、 Do not perform operations separately , So it can be nested , Make multiple judgments .
Grammar format :
if Conditional test operation 1
then
Command sequence 1
elif Conditional test operation 2
then
Command sequence 2
else
Command sequence 3
fi
Excellent students are distinguished according to the test scores entered , qualified , Unqualified third gear
vim gradediv.sh
#!/bin/bash
read -p " Please enter your score (0-100):" GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ]
then
echo "$GRADE branch , good !"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ]
then
echo "$GRADE branch , qualified !"
else
echo "$GRADE branch , unqualified !"
fi
chmod +x gradediv.sh
./gradediv.sh
3、 Extract performance monitoring indicators ( Disk usage 、CPU Use 、 Memory usage )
(1) Use df The command extracts the disk occupancy of the root partition , Assign a value to a variable DUG.
Use mpstat Command extraction CPU Usage rate , Assign a value to a variable CUG.
Use free The command extracts the memory usage , Assign a value to a variable MUG.
vim /root/sysmon.sh
#!/bin/bash
# Extract performance monitoring indicators ( Disk usage 、CPU Use 、 Memory usage )
DUG=$(df -h | grep "/$" | awk '{print $5}' | awk -F% '{print $1}')
CUG=$(expr 100 - $(mpstat | tail -1 | awk '{print $12}' | awk -F. '{print $1}'))
MUG=$(expr $(free | grep "Mem:" | awk '{print $3}') \* 100 / $(free | grep "Mem:" | awk '{print $2}'))
# Set the alarm log file 、 Alarm mailbox
ALOG="/tmp/alert.txt"
AMAIL="root"
# Judge whether the alarm is recorded
if [ $DUG -gt 90 ]
then
echo " Disk occupancy :$DUG %" >> $ALOG
fi
if [ $CUG -gt 80 ]
then
echo "CPU Usage rate :$CUG %" >> $ALOG
fi
if [ $MUG -gt 90 ]
then
echo " Memory usage :$MUG %" >> $ALOG
fi
# Judge whether to send alarm email , Finally, delete the alarm log file
if [ -f $ALOG ]
then
cat $ALOG | mail -s "Host Alert" $AMAIL
rm -rf $ALOG
fi
chmod +x /root/sysmon.sh
/root/sysmon.shDisk usage 80%、CPU Usage rate 90%、 Memory usage 90% Will send to /tmp/alert.txt Send a warning email ,( You can reduce the value as 2、3、4 Executing script tests )
(2) View the result of executing the command ,
mail
exit ( sign out ) (3) Set up crontab Planning tasks
systemctl status crond ( green running Indicates running )
crontab –e
*/30 * * * * /root/sysmon.sh ( Call every half an hour sysmon.sh Script program )
边栏推荐
- Understanding of array and bubbling
- Getting to know Alibaba cloud environment construction for the first time: unable to connect remotely, and having been in the pit: the server Ping fails, FTP is built, the server builds the database,
- Shell脚本for、while循环语句、猜价格小游戏
- How to do a good job of test case review
- Swagger -- the most popular API framework in the world
- [solved] after referring to the local MySQL and forgetting the password, [server] --initialize specified but the data directory has files in it Aborti
- 数组、冒泡的认识
- 摇摆摇摆~防火墙
- module_init函数底层原理
- Array transformer blocking idea
猜你喜欢

Echo -e usage

Full link voltage measurement

FTP service

shell脚本之条件语句

RIP综合实验

WINRAR命令拷贝指定文件夹为压缩文件,调用计划任务进行备份。

HCIA总结

Getting to know Alibaba cloud environment construction for the first time: unable to connect remotely, and having been in the pit: the server Ping fails, FTP is built, the server builds the database,

单片机之数码管秒表的动态显示

MySQL初探
随机推荐
Dynamic display of digital tube stopwatch of single chip microcomputer
HCIA总结
PHP pseudo protocol for command execution
NAT综合实验
DNS域名解析
HCIP第一天_HCIA复习
How to add software shortcuts to the right mouse button list
OSPF综合实验
HCIA_OSPF实验
echo -e用法
Next array - circular section
MySQL差删改查用户登录修改密码
MySQL初探
ctfhub--ssrf
认识交换机以及作用
Performance test implementation specification Guide
Reflection and Discussion on time management methods
Swing swing ~ firewall
Network layer transmission protocol (detailed)
Shell编程规范与变量