shell脚本02
if 条件语句
if 条件语句实践
检测sshd服务是否运行,如果未运行则启动sshd服务。如果运行,输出 “Running”。
[root@webapp ~ 17:03:10]# vim ./ssh_ctl_if_1.sh
#!/bin/bash
systemctl is-active sshd &>/dev/null
return_count=$?if (( return_count!=0 ));thenecho "Sshd is not running."echo -n "Starting sshd ... "systemctl start sshd && echo Success || echo Fail
elseecho "Sshd is running."#echo -n "Stopping sshd ... "#systemctl stop sshd && echo Success || echo Fail
fi
通过传参控制sshd服务。
[root@webapp ~ 17:03:19]# vim ssh_ctl_if_3.sh
#!/bin/bashif [ "$1" = "start" ];thensystemctl $1 sshd
elif [ "$1" = "stop" ];thensystemctl $1 sshd
elif [ "$1" = "status" ];thensystemctl $1 sshd
elseecho "Usage: $0 start|stop|status"
fi
实践
需求:每1分钟检查一次系统可用内存,如果空闲内存低于100M时给root用户发邮件。
1. 每1分钟运行一次脚本 cron定时任务完成
2. 检查内存 free -m | awk '/Mem/ {print $4}'
3. 发邮件 mailx,具体命令示例 mail -s "test" root < /etc/hosts
[root@webapp ~ 17:06:59]# crontab -e
* * * * * /root/bin/check_memory.sh[root@webapp bin 17:08:52]# vim check_memory.sh
#!/bin/bash
memory_available_size=$(free -m | awk '/Mem/ {print $NF}')
memory_min_size=10000
if ((memory_free_size<memory_min_size));thenecho "Current available memory size is ${memory_available_size}" | \mail -s "memory size is lower" root
fi
case条件语句
给输出的字符串加颜色
[root@webapp bin 17:11:52]# vim case2.sh
#!/bin/bash
case $1 inPASS)echo -e '\033[1;32mPASS\033[0;39m';;FAIL)echo -e '\033[1;31mFAIL\033[0;39m';;DONE)echo -e '\033[1;35mDONE\033[0;39m';;*)echo "Usage: $0 PASS|FAIL|DONE";;
esac
管理用户
通过传参的方式往 /etc/users 里添加用户,具体要求如下。
-
命令用法为:
Usage: user-mgr [ [-add|-a ] | [ -d|-del ] | [ -s|-search ] ] username
-
传参要求为:
- 参数为-add|-a时,表示添加后面接的用户名。如果有同名的用户, 则不能添加。
- 参数为-del|-d时,表示删除后面接的用户名。如果用户不存在,提示用户不存在。
- 参数为-search|-s时,表示查找后面接的用户名。 如果用户不存在,提示用户不存在。
- 没有用户时应给出明确提示。
[root@webapp bin 14:49:57]# vim user-mgr.sh
#!/bin/bash# run as root
[ $UID -ne 0 ] && echo 'Please run as root' && exit 1# create users file
users_info_file=/etc/users
[ -f ${users_info_file} ] || touch ${users_info_file}# provides two args
if [ $# -ne 2 ];thenecho "Usage: user-mgr [ [-add|-a ]ca | [ -d|-del ] | [ -s|-search ] ] username"exit 2
fi# get arg value
action=$1
username=$2
# manager user
case $action in-s|-search)if grep -q "username: $username" ${users_info_file};thenecho "$username is exist."elseecho "$username is not exist."fi;;-a|-add)if grep -q "username: $username" ${users_info_file};thenecho "$username is exist."elsechattr -i ${users_info_file} echo "username: $username" >> ${users_info_file}echo "$username has been added."chattr +i ${users_info_file} fi;;-d|-del)if grep -q "username: $username" ${users_info_file};thenchattr -i ${users_info_file} sed -i "/username: $username/d" ${users_info_file}chattr +i ${users_info_file} echo "$username has been deleted."elseecho "$username is not exist."fi;;*)echo "Usage: user-mgr [ [-add|-a ] | [ -d|-del ] | [ -s|-search ] ] username" ;;
esac
验证
[root@webapp bin 14:50:28]# cat /etc/users[root@webapp bin 14:51:55]# bash user-mgr.sh -s zlx
zlx is not exist.[root@webapp bin 14:52:21]# bash user-mgr.sh -s zlxx
zlxx is exist.
[root@webapp bin 14:52:46]# cat /etc/users
username: zlxx
while循环语句
while 循环语句会对紧跟在while命令后的条件表达式进行判断:
- 如果该条件表达式成立,则执行while 循环体里的命令或语句(即语法中do和done之间的指令),每一次执行到done时就会重新判断while条件表达式是否成立,直到条件表达式不成立时才会跳出while 循环体。
- 如果一开始条件表达式就不成立,那么程序就不会进入循环体(即语法中do和done之间的部分)中执行命令了。
示例:每次工作赚100w,赚到1000w就停止工作
[root@webapp bin 14:52:55]# vim makemoney.sh
#!/bin/bashmoney=0
target=10000000
while [ $money -lt $target ]
doecho -n "I'm working hard ... total: "money=$[ money+1000000 ]echo $moneysleep 0.5
done
[root@webapp bin 15:33:19]# bash makemoney.sh
I'm working hard ... total: 1000000
I'm working hard ... total: 2000000
I'm working hard ... total: 3000000
I'm working hard ... total: 4000000
I'm working hard ... total: 5000000
I'm working hard ... total: 6000000
I'm working hard ... total: 7000000
I'm working hard ... total: 8000000
I'm working hard ... total: 9000000
I'm working hard ... total: 10000000
示例2: 后台监视sshd服务,一旦发现sshd服务未运行,就start sshd。每隔3秒检测一次。不允许使用计划任务(cron)。
[root@webapp bin 15:41:34]# vim jianshi.sh#!/bin/bash
while true
dosystemctl is-active sshd &>/dev/nullreturn_count=$?if (( return_count!=0 ));thensystemctl start sshd elsesleep 3fi
done
验证:
#关闭sshd服务
[root@webapp ~ 15:40:43]# systemctl stop sshd
#检查sshd服务状态
[root@webapp ~ 15:42:05]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: inactive (dead) since 五 2025-10-10 15:41:47 CST; 27s agoDocs: man:sshd(8)man:sshd_config(5)Process: 20298 ExecStart=/usr/sbin/sshd -D $OPTIONS (code=exited, status=0/SUCCESS)Main PID: 20298 (code=exited, status=0/SUCCESS)#启动脚本
[root@webapp bin 15:40:14]# bash jianshi.sh#再次检查sshd服务状态
[root@webapp ~ 15:42:15]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since 五 2025-10-10 15:42:24 CST; 5s agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 22551 (sshd)Tasks: 1CGroup: /system.slice/sshd.service└─22551 /usr/sbin/sshd -D#用指令关闭sshd服务后再检查sshd服务状态,发现sshd关闭后很快就会被再次启动
[root@webapp ~ 15:41:25]# systemctl stop sshd
[root@webapp ~ 15:42:15]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since 五 2025-10-10 15:42:24 CST; 5s agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 22551 (sshd)Tasks: 1CGroup: /system.slice/sshd.service└─22551 /usr/sbin/sshd -D
.service; enabled; vendor preset: enabled)
Active: active (running) since 五 2025-10-10 15:42:24 CST; 5s ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 22551 (sshd)
Tasks: 1
CGroup: /system.slice/sshd.service
└─22551 /usr/sbin/sshd -D