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

北慕城南 提交于 2020-12-28 21:06:34

问题


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.

I need to achieve this on AIX server with bash.


回答1:


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.

Edit in response to comments:

Change your original script to this:

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



回答2:


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

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



来源:https://stackoverflow.com/questions/14894605/shell-script-to-create-folder-daily-with-time-stamp-and-push-time-stamp-generate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!