将后缀名为 .txt 的文件改成 .log

[root@k8s-master test]# touch localhost_2020-01-{02..26}.txt
[root@k8s-master test]# ll
total 0
-rw-r--r-- 1 root root 0 Aug 27 16:26 localhost_2020-01-02.txt
-rw-r--r-- 1 root root 0 Aug 27 16:26 localhost_2020-01-03.txt
-rw-r--r-- 1 root root 0 Aug 27 16:26 localhost_2020-01-04.txt # 此例中, ${filename//\.txt/\.log} 或 ${filename/\.txt/\.log} 都可以,如果变量名中有多个 .txt,前者全部替换,后者只替换第一个
[root@k8s-master test]# for filename in `ls ./`;do mv $filename ${filename//\.txt/\.log};done
[root@k8s-master test]# ll
total 0
-rw-r--r-- 1 root root 0 Aug 27 16:26 localhost_2020-01-02.log
-rw-r--r-- 1 root root 0 Aug 27 16:26 localhost_2020-01-03.log
-rw-r--r-- 1 root root 0 Aug 27 16:26 localhost_2020-01-04.log

输入一个用户,判断 Linux 系统中是否存在此用户

[root@k8s-master 827]# cat check_user.sh
#!/bin/bash read -p "Check username is or not exist : " username grep -e "^$username\:" /etc/passwd >/dev/null if [ $? -eq 0 ];then
echo "Yes! It's exist!"
else
echo "No ! It's not exist"
fi

猜年龄,年龄是整形数字

[root@k8s-master 827]# cat guess_age.sh
#!/bin/bash correct_age=18 # 检查是否输入一个位置参数
[ $# -ne 1 ] && echo "Please Input One Argument ~~~ " && exit # 检查参数是否是数字
[[ ! $1 =~ ^[0-9]+$ ]] && echo "Argument Must Be Integer ~~~ " && exit # 判断是否正确
if [ $1 -eq $correct_age ];then
echo "Congratulation ~~~"
elif [ $1 -gt $correct_age ];then
echo "Greater Than Correct Resault !!! "
elif [ $1 -lt $correct_age ];then
echo "Less Than Correct Resault !!! "
fi

监控磁盘和内存的使用情况

[root@k8s-master 827]# cat monitor.sh
#!/bin/bash # 获取磁盘已使用量
disk_use=`df | grep '/$' | awk '{print $5}' | cut -d% -f1`
# 获取内存总量,内存空闲
mem_total=`free -m | grep "Mem" | awk '{print $2}'`
mem_free=`free -m | grep "Mem" | awk '{print $4}'`
# 获取内存空闲百分比
mem_free_percent=$(echo "scale=2;$mem_free/$mem_total" | bc | cut -d. -f2) # 磁盘用量大于 80% 时,发送邮件提醒
if [ $disk_use -gt 80 ];then
echo "磁盘使用${disk_use}%,清理下磁盘吧 ~~~" | mail -s "Warning,Check Your Disk Status" xxxx@126.com
fi # 内存用量大于 80% 时,发送邮件提醒
if [ $mem_free_percent -lt 20 ];then
echo "内存剩余${mem_free_percent}%, 内存不够用了 ~~~" | mail -s "Warning,Check Your Memory Status" xxxx@126.com
fi

写一个脚本,模拟 Nginx 服务启动等操作

[root@k8s-master 827]# cat nginx.sh
#!/bin/bash . /etc/init.d/functions # 需要定义一个全局变量,位置参数无法传递到函数体内
arg=$1 # 判断执行命令是否成功,并给出响应结果
function check(){
systemctl $1 nginx &>/dev/null
[ $? -eq 0 ] && action "Nginx $arg is" true || action "Nginx $arg is" false
} # 判断是否传入一个位置参数
[ $# -ne 1 ] && echo -e "Usage: $0 { start | restart | stop | reload | status } " && exit # 根据传入的位置参数 选择执行命令
case $1 in
"start")
# 检查是否已经启动
netstat -an | grep '\bLISTEN\b' | grep '\b80\b' &>/dev/null
if [ $? -eq 0 ];then
action "Nginx is already started" true
else
check
fi
;;
"restart")
check
;;
"status")
check
;;
"stop")
check
;;
"reload")
check
;;
*)
echo -e "Usage: $0 { start | restart | stop | reload | status } "
esac

判断数字是否是整型

[root@k8s-master 826]# cat isint.sh
#!/bin/bash # 获取用户终端输入
read -p "Please Input Your Number:" number # 判断输入是否是整型
expr $number + 0 &>/dev/null
[ $? -eq 0 ] && echo "Type Int!" || echo "SHIT!!"

测试传入的 IP 地址能否 PING 通

[root@k8s-master 826]# cat ping.sh
#!/bin/bash
# 循环获取所有的位置参数
for i in "$@"
do
# 在 子shell 中运行,并放到后台,可以脚本并发执行
(ping -c 1 $i &>/dev/null ;[ $? == 0 ] && echo "$i : successful" >> ./ping.log || echo "$i : failure" >> ./ping.log) &
done [root@k8s-master 826]#./ping.sh baidu.com 172.16.1.151 1.1.1.1 172.16.1.153
[root@k8s-master 826]# cat ping.log
172.16.1.151 : successful
baidu.com : successful
1.1.1.1 : successful
172.16.1.153 : failure

普通运算,要求数字可以为整型和浮点型

[root@k8s-master 826]# cat arithmetic.sh
#!/bin/bash # 判断传了几个参数
[ $# -ne 2 ] && echo "请输入两位数字信息" && exit # 定义变量,方便调用
a=$1
b=$2 # 运算
echo "a-b=$[$a-$b]"
echo "a+b=$[$a+$b]"
echo "a*b=$[$a*$b]"
echo "a%b=$[$a%$b]"
# 除法运算
# 判断小数点前是否有数字,如果结果小于 1,bc 运算结果小数点前没有数字
if [ -z $(echo "scale=2;$a/$b"| bc | cut -d. -f1 ) ];then
# 如果结果小于 1,补一个 0(字符),bc 运算结果小于 0 时,会省略 0
echo "0$(echo "scale=2;$a/$b"| bc )"
else
# 如果结果大于 1,正常输出即可
echo "$(echo "scale=2;$a/$b"| bc )"
fi

传递两个两位数(整型),做运算,要求除法结果保留两位小数

#!/bin/bash

# 判断传了几个参数
[ $# -ne 2 ] && echo "请输入两位数字信息" && exit # 判断是否是两位的整型数字
[ ${#1} -ne 2 ] || [[ ! $1 =~ ^[0-9][0-9]$ ]] && echo "只能是两位数且为整型" [ ${#2} -ne 2 ] || [[ ! $2 =~ ^[0-9][0-9]$ ]] && echo "只能是两位数且为整型" # 定义变量,方便调用
a=$1
b=$2 # 运算
echo "a-b=$[$a-$b]"
echo "a+b=$[$a+$b]"
echo "a*b=$[$a*$b]"
# 做判断,可以获取 2 个小数位
if [ -z $(echo "scale=2;$a/$b"| bc | cut -d. -f1 ) ];then
echo "0$(echo "scale=2;$a/$b"| bc )"
else
echo "$(echo "scale=2;$a/$b"| bc )"
fi
echo "a%b=$[$a%$b]"

传入两个参数,对比两个数字的大小,要求数字可以为整型和浮点型

[root@k8s-master 826]# cat comparenum.sh
#!/bin/bash # 判断用户输入了 2 个参数
if [ $# -ne 2 ];then
echo "需要输入两个参数啊"
exit
fi
# 判断用户输入的 2 个参数都是数字
if [[ ! $1 =~ ^[0-9]+$ ]] && [[ ! $1 =~ ^[0-9]+\.[0-9]+$ ]];then
echo "第一个参数得是数字啊"
exit
fi if [[ ! $2 =~ ^[0-9]+$ ]] && [[ ! $2 =~ ^[0-9]+\.[0-9]+$ ]];then
echo "第二个参数得是数字啊"
exit
fi # 对比两个参数(数字)大小
if [[ $1 =~ ^[0-9]+$ ]] && [[ $2 =~ ^[0-9]+$ ]];then
# 对比整型数字大小
[[ $1 -eq $2 ]] && echo "$1 = $2"
[[ $1 -gt $2 ]] && echo "$1 > $2"
[[ $1 -lt $2 ]] && echo "$1 < $2"
else
# 对比浮点型数字大小
[[ $(echo "$1 == $2" | bc) -eq 1 ]] && echo "$1 = $2"
[[ $(echo "$1 > $2" | bc) -eq 1 ]] && echo "$1 > $2"
[[ $(echo "$1 < $2" | bc) -eq 1 ]] && echo "$1 < $2"
fi

模拟用户登录终端

#!/bin/bash

db_username="root"
db_password="123"
counts=0 function tty(){
while :
do
read -p "[root@website $(pwd)]# " cmd
$cmd
done
} while :
do
read -p "Please Input Your Username : " username
read -p "Please Input Your Password : " password
username=${username:=NULL}
password=${password:=NULL}
# 判断登录是否成功
if [ $username == $db_username -a $password == $db_password ];then
# 成功,退出循环
echo "[ Successful ] Login ! "
break
else
# 失败,提示还可以尝试的次数
[ $counts -ne 2 ] && echo "[ Info ] You have only $[2-counts] times left !"
# 判断用户名错误还是密码错误。给予提示
if [ $username != $db_username ];then
echo "[ Warning ] The Username does't exist ! "
else
[ $password != $db_password ] && echo "[ Warning ] Wrong Password ! "
fi
[ $counts -eq 2 ] && exit
fi
let counts++
done tty

模仿红绿灯

[root@abc 901]# cat signal.sh
#!/bin/bash
# 清屏
clear
#
count=0 while :
do
if [ $(expr $count % 3) -eq 0 ];then
# 红灯亮时间
red_time=5
while :
do
echo -e "\033[31m 红灯亮 ${red_time} \033[0m"
sleep 1
clear
let red_time--
[ $red_time -eq -1 ] && break
done
elif [ $(expr $count % 3) -eq 1 ];then
# 绿灯亮时间
green_time=3
while :
do
echo -e "\033[32m 绿灯亮 ${green_time} \033[0m"
sleep 1
clear
let green_time--
[ $green_time -eq -1 ] && break
done
else
# 黄灯亮时间
yellow_time=2
while :
do
echo -e "\033[33m 黄灯亮 ${yellow_time} \033[0m"
sleep 1
clear
let yellow_time--
[ $yellow_time -eq -1 ] && break
done fi
let count++
done

服务器状态监控

先编写一个可发送邮件的 Python 程序:

# python 脚本,放在 /usr/bin/ 目录下
[root@k8s-master01 monitor_mail]# cat /usr/bin/mail
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import smtplib
import email.mime.multipart
import email.mime.text server = 'smtp.163.com'
port = '25' def sendmail(server,port,user,pwd,msg):
smtp = smtplib.SMTP()
smtp.connect(server,port)
smtp.login(user, pwd)
smtp.sendmail(msg['from'], msg['to'], msg.as_string())
smtp.quit()
print('Email has send out !!!~~~') if __name__ == '__main__':
msg = email.mime.multipart.MIMEMultipart()
msg['Subject'] = 'Monitor Warning Mail !!!'
msg['From'] = 'wqh1XXXXX@163.com'
msg['To'] = 'wqh2XXXXX@126.com'
user = 'wqh1XXXXX'
pwd = 'XXXXXXXXXX'
# 格式处理,专门针对我们的邮件格式
content='%s\n%s' %('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:])) txt = email.mime.text.MIMEText(content, _charset='utf-8')
msg.attach(txt) sendmail(server,port,user,pwd,msg)

监控脚本:

# bash 脚本,可以用定时任务执行
[root@k8s-master01 monitor_mail]# cat monitor.sh
#!/bin/bash # CPU阈值
cpu_limit=0
# 内存阈值
mem_limit=0
# 监控的磁盘分区
disk_name="/dev/sda3"
# 磁盘容量阈值
disk_block_limit=0
# 磁盘Inode阈值
disk_inode_limit=0 function monitor_cpu() {
cpu_free=$(vmstat 1 5 | awk 'NR>=3{x=x+$15}END{print x/5}' | cut -d. -f1)
cpu_used=$(echo "scale=0;100-${cpu_free}" | bc)
cpu_stat=$cpu_used
if [ $cpu_stat -gt $cpu_limit ];then
msg=" DATETIME: $(date +%F_%T)
HOSTNAME: $(hostname)
IPADDR: $(hostname -I| awk '{print $1}')
WARNING:
CPU usage exceeds the limit,current value is ${cpu_stat}% !!!
"
fi
echo -e $msg
/usr/bin/mail $msg
} function monitor_mem() {
mem_total=$(free | awk 'NR==2{print $2}')
mem_used=$(free | awk 'NR==2{print $3}')
mem_stat=$(echo "scale=2;${mem_used}/${mem_total}" | bc | cut -d. -f2)
if [ $mem_stat -gt $mem_limit ];then
msg=" DATETIME: $(date +%F_%T)
HOSTNAME: $(hostname)
IPADDR: $(hostname -I| awk '{print $1}')
WARNING:
Memory usage exceeds the limit,current value is ${mem_stat}% !!!
"
fi
echo -e $msg
/usr/bin/mail $msg
} function monitor_disk_block() {
disk_block_used=$(df | awk 'NR==6{print $5}'|cut -d% -f1)
disk_block_stat=$disk_block_used
if [ $disk_block_stat -gt $disk_block_limit ];then
msg=" DATETIME: $(date +%F_%T)
HOSTNAME: $(hostname)
IPADDR: $(hostname -I| awk '{print $1}')
WARNING:
Disk Block usage exceeds the limit,current value is ${disk_block_stat}% !!!
"
fi
echo -e $msg
/usr/bin/mail $msg
} function monitor_disk_inode() {
disk_inode_used=$(df -i | awk 'NR==6{print $5}'|cut -d% -f1)
disk_inode_stat=$disk_inode_used
if [ $disk_inode_stat -gt $disk_inode_limit ];then
msg=" DATETIME: $(date +%F_%T)
HOSTNAME: $(hostname)
IPADDR: $(hostname -I| awk '{print $1}')
WARNING:
Disk Inode usage exceeds the limit,current value is ${disk_inode_stat}% !!!
"
fi
echo -e $msg
/usr/bin/mail $msg
} monitor_cpu &>> /tmp/monitor.log
monitor_mem &>> /tmp/monitor.log
monitor_disk_inode &>> /tmp/monitor.log
monitor_disk_block &>> /tmp/monitor.log

Shell 编程练习的更多相关文章

  1. Linux学习笔记(17) Shell编程之基础

    1. 正则表达式 (1) 正则表达式用来在文件中匹配符合条件的字符串,正则是包含匹配.grep.awk.sed等命令可以支持正则表达式:通配符用来匹配符合条件的文件名,通配符是完全匹配.ls.find ...

  2. shell编程:定义简单标准命令集

    shell是用户操作接口的意思,操作系统运行起来后都会给用户提供一个操作界面,这个界面就叫shell,用户可以通过shell来调用操作系统内部的复杂实现,而shell编程就是在shell层次上进行编程 ...

  3. Linux Shell编程入门

    从程序员的角度来看, Shell本身是一种用C语言编写的程序,从用户的角度来看,Shell是用户与Linux操作系统沟通的桥梁.用户既可以输入命令执行,又可以利用 Shell脚本编程,完成更加复杂的操 ...

  4. Shell编程菜鸟基础入门笔记

    Shell编程基础入门     1.shell格式:例 shell脚本开发习惯 1.指定解释器 #!/bin/bash 2.脚本开头加版权等信息如:#DATE:时间,#author(作者)#mail: ...

  5. Linux_10------Linux之shell编程------变量

    .-9 vim num.sh #! /bin/bash num1=$1 num2=$2 sum=$(($num1+$num2)) #变量sum是num1和num2的综合 echo $sum 执行 ./ ...

  6. 需要交互的shell编程——EOF(转载)

    在shell编程中,”EOF“通常与”<<“结合使用,“<<EOF“表示后续的输入作为子命令或子shell的输入,直到遇到”EOF“, 再次返回到主调shell,可将其理解为分 ...

  7. ****CodeIgniter使用cli模式运行,把php作为shell编程

    shell简介 在计算机科学中,Shell俗称壳(用来区别于核).而我们常说的shell简单理解就是一个命令行界面,它使得用户能与操作系统的内核进行交互操作. 常见的shell环境有:MS-DOS.B ...

  8. Shell 编程基础之变量和环境变量

    一.变量赋值和引用 Shell 编程中,使用变量无需事先声明,同时变量的命名不惜遵循如下规则: 首个字符必须为字母(a-z,A-Z)或者_ 变量名中间不能有空格,可以使用_连接 不能使用其他表达符号 ...

  9. Linux Shell编程基础

    在学习Linux BASH Shell编程的过程中,发现由于不经常用,所以很多东西很容易忘记,所以写篇文章来记录一下 ls   显示当前路径下的文件,常用的有 -l 显示长格式  -a 显示所有包括隐 ...

  10. centos 下建用户 shell编程

    useradd 用户名 passwd 用户名 cat /etc/passwd  查看用户信息 删除用户 userdel -r   加一个 -r 表示把用户及用户的主目录都删除 su  切换用户 sud ...

随机推荐

  1. Python利用最优化算法求解投资内部收益率IRR【一】

    一. 内部收益率和净现值 内部收益率(Internal Rate of Return, IRR)其实要和净现值(Net Present Value, NPV)结合起来讲.净现值指的是某个投资项目给公司 ...

  2. 1.5V升5V芯片,1.5V升5V电路图规格书

    常用的 5号,7号等 1.5V 干电池满电电压在 1.6V 左右,干电池输出耗电电压在 1V.适用PW5100,在 0.9V 时还能输出,彻底榨干干电池的电量. 1.5V 升5V 的芯片:PW5100 ...

  3. torch.optim.SGD()各参数的解释

    看pytorch中文文档摘抄的笔记. class torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, neste ...

  4. redis list 列表 查找 时间复杂度

    http://redisbook.com/preview/intset/content.html 列表对象 列表对象的编码可以是 ziplist 或者 linkedlist . ziplistFind ...

  5. status http status code 状态码

    RFC 6585 - Additional HTTP Status Codes https://tools.ietf.org/html/rfc6585 https://developer.mozill ...

  6. py, pyc, pyw, pyo, pyd Compiled Python File (.pyc) 和Java或.NET相比,Python的Virtual Machine距离真实机器的距离更远

    https://my.oschina.net/renwofei423/blog/17404 1.      PyCodeObject与Pyc文件 通常认为,Python是一种解释性的语言,但是这种说法 ...

  7. JavaScript与多线程的不解之缘!

    前言 对于前端开发者来说,多线程是一个比较陌生的话题.因为JavaScript是单线程语言.也就是说,所有任务只能在一个线程上完成,一次只能做一件事.前面的任务没做完,后面的任务只能等着. UI渲染与 ...

  8. Maven环境搭建以及在IDEA中的配置与简单入门

    目录 一.下载与安装 二.配置 1. 环境变量 2. 阿里云镜像 3. 本地仓库 三.IDEA创建Maven项目 1. 创建一个原始的Maven项目 1.2 指定模板创建(可选) 2. 配置GAV 3 ...

  9. 虚函数表-C++多态的实现原理

    目录 1.说明 2.虚函数表 3.代码示例 参考:http://c.biancheng.net/view/267.html 1.说明 我们都知道多态指的是父类的指针在运行中指向子类,那么它的实现原理是 ...

  10. Display属性学习总结

    HTMl元素根据表现形式,常见的可以分为两类. (1)块元素(block) (2)行内元素(inline). 当然,除了以上两种元素类型外,还有inline-block.table-cell等元素类型 ...