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

user1746666 picture user1746666 · Feb 15, 2013 · Viewed 49.5k times · Source

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.

Answer

user000001 picture user000001 · Feb 15, 2013

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