Shell脚本每天创建带有时间戳的文件夹,并推送时间戳生成的日志
问题描述:
我有一个cron作业,该作业每30分钟运行一次,以生成带有时间戳的日志文件,如下所示:
I have a cron job which runs every 30 minutes to generate log files with time-stamp like this:
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.
我需要使用bash在AIX服务器上实现此目标.
I need to achieve this on AIX server with bash.
答
也许您正在寻找这样的脚本:
Maybe you are looking for a script like this:
#!/bin/bash
shopt -s nullglob # This line is so that it does not complain when no logfiles are found
for filename in test*.log; do # Files considered are the ones starting with test and ending in .log
foldername=$(echo "$filename" | awk '{print (substr($0, 5, 8));}'); # The foldername is characters 5 to 13 from the filename (if they exist)
mkdir -p "$foldername" # -p so that we don't 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.
根据评论进行
将原始脚本更改为此:
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
或者如果目录是在其他地方创建的,只需执行以下操作:
Or if the directory is created somewhere else, just do this:
sh sample.sh > /home/app/logs/$(date +%Y%m%d)/test$(date +%Y%m%d%H%M%S).log