bash shell 脚本每天创建带有时间戳的文件夹并推送时间戳生成的日志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14894605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:20:11  来源:igfitidea点击:

shell script to create folder daily with time-stamp and push time-stamp generated logs

bashshellunixcronaix

提问by user1746666

I have a cron job which runs every 30 minutes to generate log files with time-stamp like this:

我有一个 cron 作业,它每 30 分钟运行一次,以生成带有时间戳的日志文件,如下所示:

test20130215100531.log, 
test20130215102031.log  

I would like to create one folder daily with date time-stamp and push log files in to respective date folder when generated.

我想每天创建一个带有日期时间戳的文件夹,并在生成时将日志文件推送到相应的日期文件夹中。

I need to achieve this on AIX server with bash.

我需要使用 bash 在 AIX 服务器上实现这一点。

回答by user000001

Maybe you are looking for a script like this:

也许您正在寻找这样的脚本:

#!/bin/bash

shopt -s nullglob  # this line is so that it does not compain when no logfiles are found
for filename in test*.log; do # Files considered are the ones startign with test and ending in .log
    foldername=$(echo "$filename" | awk '{print (substr(
foldername=$(date +%Y%m%d)
mkdir -p  /home/app/logs/"$foldername"
sh sample.sh > /home/app/logs/"$foldername"/test$(date +%Y%m%d%H%M%S).log
, 5, 8));}'); # The foldername is characters 5 to 13 from the filename (if they exist) mkdir -p "$foldername" # -p so that we dont get "folder exists" warning mv "$filename" "$foldername" echo "$filename $foldername" ; done

I only tested with your sample, so do a proper testing before using in a directory that contains important stuff.

我只用您的样本进行了测试,因此在包含重要内容的目录中使用之前,请进行适当的测试。

Edit in response to comments:

编辑回应评论:

Change your original script to this:

将您的原始脚本更改为:

sh sample.sh > /home/app/logs/$(date +%Y%m%d)/test$(date +%Y%m%d%H%M%S).log

Or it the directory is created somewhere else, just do this:

或者目录是在其他地方创建的,只需执行以下操作:

##代码##

回答by Billy Lazzaro

You should use logrotate! It can do this for you already, and you can just write to the same log file.

你应该使用 logrotate!它已经可以为您执行此操作,您只需写入同一个日志文件即可。

Check their man pages for info: http://linuxcommand.org/man_pages/logrotate8.html

检查他们的手册页以获取信息:http: //linuxcommand.org/man_pages/logrotate8.html