您的位置 首页 php

linux下的shell脚本编程介绍

Shell 编程语言的介绍

  • shell简介:

Shell是一种 脚本语言 ,又是一种命令语言。可以通俗一点来讲, Shell脚本 就是一系列命令的集合,可以在 Unix / linux 上面直接使用,并且直接调用大量系统内部的功能来解释执行程序把一些重复性工作交给shell做,来实现自动化运维。

Shell 虽然没有C/C++、 Java Python 等强大,但也支持了基本的编程元素。例如: if 、for、while、case等循环,还有变量、数组、 字符串 、注释、加减乘除逻辑运算等

  • 常见的脚本语言:

shell、perl、php、python

  • shell的优点:

易用 #直接在linux系统上使用,不需要编译

高效 #程序开发的效率非常高,依赖于功能强大的命令可以迅速地完成开发任务

简单 #语法和结构比较简单,易于掌握

  • shell 应用场景:

监控linux系统的健康度

数据的处理 #日志的切割、分析、统计等

与数据库交互 #对数据库进行增,删,改,查等操作

监控进程,自动化启停服务

完成一些重复性的工作

shell编写第一个脚本

  • 编写:vi first.sh
 # !/bin/bash
# 作者:菜园子
# 编写时间:2022-09-21
# 功能:我的第一个shell脚本
echo "this is my first shell !"  
  • 执行:
 sh first.sh
chmod 755 first.sh
./first.sh  

企业实战之shell脚本与crontab定时器的运用

  • crond服务:

以守护进程方式在无需人工干预的情况下来处理着一系列作业和指令的服务

  • crond服务的启停命令
 启动
systemctl start crond.service
查看状态:
systemctl status crond.service
停止
systemctl stop crond.service
重新启动
systemctl restart crond.service  
  • crontab 定时器的使用
 语法:crontab 【选项】
crontab -l #列出crontab有哪些任务
crontab -e #编辑crontab任务
crontab -r #删除crontab里的所有任务

内容格式:
* * * * * 级别 命令
分 时 日 月 周  
  • crontab的例子
 每分钟执行
* * * * * 或者 */1 * * * *

每小时执行
0 * * * *

每天执行
0 0 * * *

每周执行
0 0 * * 0

每月执行
0 0 1 * *

每年执行
0 0 1 1 *

每天早上6点执行
0 6 * * *

每两个小时执行
0 */2 * * *

每小时的10分,40分执行
10,40 * * * *

每天的下午4点、5点、6点的5 min、15 min、25 min、35 min、45 min、55 min时执行命令
5,15,25,35,45,55 16,17,18 * * *  

利用shell脚本企业实战 nginx 日志切割

需求:

  • nginx的日志文件路径
  • 每天0点对nginx 的access与error日志进行切割
  • 以前一天的日期为命名

脚本:

 #!/bin/bash
#Auto cut nginx log  script .
#Create by Cyz
#Create date : 2022-09-21

#nginx日志路径
logs_path=/usr/local/nginx/logs
YesterDay=$(date -d 'yesterday' +%Y-%m-%d)

#移动日志并以日期改名
mv ${logs_path}/access.log ${logs_path}/access_${YesterDay}.log
mv ${logs_path}/error.log ${logs_path}/error_${YesterDay}.log

#向nginx主进程发送信号,重新生成日志文件
kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid)  

个人博客:

文章来源:智云一二三科技

文章标题:linux下的shell脚本编程介绍

文章地址:https://www.zhihuclub.com/153157.shtml

关于作者: 智云科技

热门文章

网站地图