shell脚本实例
背景
centos7环境
1、获取进程pid,并且kill掉
#! /bin/bash
searchName=XXX
pids=$(ps -ef | grep ${searchName} |grep -v grep |awk '{print $2}')
for pid in ${pids}
do
echo "kill pid" $pid
kill -9 $pid
done
echo "finished ..."
#################################################
注意: grep -v grep的作用是过滤掉grep的进程,防止误删和报错
2、nginx日志切割脚本
需求:nginx的日志无限增长,导致了磁盘空间紧张
解决方案:shell脚本定时处理。
采用centos7 定时任务定时执行脚本对日志进行处理,保存近7天的日志
(1)shell脚本
#!/bin/bash
# 日志存储路径
log_path=/data/tomcats/platform-nginx/logs
# 取出昨天的时间
log_date=$(date -d yesterday +%Y-%m-%d)
# 将访问日志重命名,标志位昨天的日期
cp ${log_path}/access.log ${log_path}/access_${log_date}.log
# 清空原来的日志文件
cat /dev/null > ${log_path}/access.log
# 将错误日志重命名,标志为昨天的日期
cp ${log_path}/error.log ${log_path}/error_${log_date}.log
cat /dev/null > ${log_path}/error.log
# 只保留最近7天的日志文件,减少硬盘压力
find ${log_path} -type f -name "*.log" -ctime +7 -exec rm -f {} \;
另外的写法
cur_date=$(date +"%Y%m%d")
cd /opt/nginx/logs
zip -r ./$cur_date.zip ./*.log
for i in `find . -name '*.log'`; do cat /dev/null > $i; done
# Keep 30 backup files
find . -name '*.zip' -mtime +30 -exec rm -f {} \;
(2)脚本赋权限
chmod +x 你编写的脚本
(3)编辑系统定时任务文件
vim /etc/crontab
## 编辑添加以下内容,dev表示用户
0 0 * * * dev /data/tomcats/platform-nginx-logjob/nginx_logs.sh # 每天00:00定时执行任务
(4)重启定时任务服务
systemctl restart crond.service
3、boot启动、停止、状态脚本
#!/bin/sh
## 此处可以直接指定路径,如:CURRENT_PATH = /data/tomcats/platform-web-8081/
CURRENT_PATH=`dirname $(readlink -f $0)`
#输入参数
IMPUT_CODE=$1
start ()
{
echo "$CURRENT_PATH starting ............"
#启动脚本
#check file exist
#if [ -f "$CURRENT_PATH/jars/$JAR_NAME" ];then
if [ "`ls -A $CURRENT_PATH'/jars/'`" != "" ];then
echo 'have files'
rm $CURRENT_PATH/*.jar
mv $CURRENT_PATH/jars/*.jar $CURRENT_PATH/
fi
rm -rf $CURRENT_PATH/logs/*
BUILD_ID=dontKillMe nohup /usr/local/java/bin/java -jar $CURRENT_PATH/*.jar >/dev/null 2>&1 & ## /dev/null 将日志输入到黑洞,如果需要输入到文件,可以写:$CURRENT_PATH/out.log
}
stop ()
{
PID=$(ps -ef|grep java |grep "$CURRENT_PATH" |grep -v grep |awk '{print $2}')
if [ -n "$PID" ];then
#关闭脚本
echo "kill pid=$PID"
kill -9 $PID
fi
}
status()
{
#查看是否运行中
PID=$(ps -ef|grep java |grep "$CURRENT_PATH" |grep -v grep |awk '{print $2}')
if [ -n "$PID" ];then
echo "$CURRENT_PATH pid=$PID is running...."
else
echo "$CURRENT_PATH is stop...."
fi
}
log()
{
tail -f $CURRENT_PATH/out.log
}
#默认重启服务
if [[ -z "$1" ]];then
IMPUT_CODE=restart
fi
case "$IMPUT_CODE" in
start)
start
;;
stop)
stop
;;
log)
#restart
log
;;
restart)
stop
start
;;
status)
status
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart|status}" >&2
exit 1
;;
esac
exit 0
原文地址:https://blog.csdn.net/qq_34207898/article/details/136928052
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!