command.sh:
指令,如java -version
test.sh(后台启动test.sh,同级生成test.log):
nohup ./command.sh > test.log 2>&1 &
logDealer.sh(test.log大于40KB就删除logs/test/下所有文件,复制test.log为同级logs/test/当前时间.log,删除test.log,test.log因为有test.sh在后台执行会重新生成):
FILE=`echo test.log`
FILE_SIZE=`echo $(du $FILE) | awk '{print $1}'`
if [ $FILE_SIZE -ge 40 ]
then
cp -p $FILE logs/test/$(date "+%Y-%m-%d_%H:%M:%S").log
fi
crontab -e后vi编辑(每分钟执行一次/home/test/testProgram/test下的logDealer.sh):
*/1 * * * * /home/test/testProgram/test/logDealer.sh
编写历程(含知识点解析):
目录结构(/home/test/testProgram/test):
command.sh
test.sh
logs
testJava的System.out打印和异常对于Linux都属于标准输出流(1):
nohup ./test_1.sh > log.txt &
Java的System.err打印应该对于Linux属于标准错误流(2),待检验:
nohup ./test_1.sh > log.txt 2>&1 &
nohup ./test_1.sh > test.log 2>&1 &输出date "+%Y-%m-%d_%H:%M:%S":
echo date "+%Y-%m-%d_%H:%M:%S"
输出date "+%Y-%m-%d_%H:%M:%S"的执行结果:
echo $(date "+%Y-%m-%d_%H:%M:%S")nohup ./test_1.sh > log_$(date "+%Y-%m-%d_%H:%M:%S").txt 2>&1 &
nohup ./test_1.sh > logs/log_$(date "+%Y-%m-%d_%H:%M:%S").txt 2>&1 &
nohup ./test_1.sh > logs/test/$(date "+%Y-%m-%d_%H:%M:%S").log 2>&1 &单位:K
不显示单位:
du log.txt
显示单位:
du -sh log.txtecho $(du log.txt)
| 表示管道,上一条命令的输出,作为下一条命令的参数:
echo $(du log.txt) | awk '{print $1}'``是命令替换,指Shell可以先执行``中的命令,将输出结果保存:
FILE_SIZE=`echo $(du log.txt) | awk '{print $1}'`
echo $FILE_SIZE
等同于
echo `echo $(du log.txt) | awk '{print $1}'`1024K对应1M
-ge为大于等于
fi表示结束
[]内部两侧必须有空格FILE_SIZE=`echo $(du log.txt) | awk '{print $1}'`
if [ $FILE_SIZE -ge 10240 ]
then
echo file bigOrEqual 10M
else
echo file small 10M
fiFILE=`echo test.log`
FILE_SIZE=`echo $(du $FILE) | awk '{print $1}'`
if [ $FILE_SIZE -ge 40 ]
then
cp -p $FILE logs/test/$(date "+%Y-%m-%d_%H:%M:%S").log
fi当前目录下文件数量(参考:https://www.cnblogs.com/dbalightyear/p/11280217.html):
ls -l | grep "^-" | wc -lLOG_COUNT=`echo $(ls -l | grep "^-" | wc -l)`
echo $LOG_COUNT/*之间没有空格,否则会误删当前目录下的文件:
rm -f logs/test/*查看crontab服务状态(参考:https://blog.csdn.net/qq_39131177/article/details/79051711):
service crond status
查看crontab定时格式(参考:https://www.cnblogs.com/zhangchao0515/p/9772706.html):test.sh:
FILE=`echo test.log`
FILE_SIZE=`echo $(du $FILE) | awk '{print $1}'`
if [ $FILE_SIZE -ge 2048 ]
then
rm -f logs/test/*
cp -p $FILE logs/test/$(date "+%Y-%m-%d_%H:%M:%S").log
rm -f $FILE
fiecho "test" >> /home/test/gisProgram/test/test.txt
crontab -e
*/1 * * * * /home/test/testProgram/test/test.sh
*/1 * * * * /home/test/testProgram/test/logDealer.sh