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

54,209

Solution 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

Solution 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

Share:
54,209
user1746666
Author by

user1746666

Updated on July 09, 2022

Comments

  • user1746666
    user1746666 almost 2 years

    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.