I want to move log files which are older than two days to a new directory by date, like below.


1) /Test1/Server.log
2) /Test1/Server17032016.log



Create directories by date and move files there.

  • How you determine the new filenames? – roaima Mar 19 '16 at 19:12
  • sorry it was my mistake i m not create new file i want to just move Server17032016.log in directory 1)/Test2/17032016/ – Chirag Dhaduk Mar 19 '16 at 19:17
  • No, i want explain that'y i have put 1) and 2) but the directory is like /Test1/ or /Test2/ – Chirag Dhaduk Mar 19 '16 at 19:43
  • 2
    Maybe this is not the answer to your question but I advise reading logrotate tool documentation and using it as a tool to do the job instead of writing custom bash scripts. – KWubbufetowicz Mar 19 '16 at 19:52
  • What's supposed to happen to source file 1? It doesn't have a date suffix. – roaima Mar 19 '16 at 21:18

I'd suggest you don't perform backups with the modified date.

Wouldn't you prefer to sort your backups on the day when they actually were backed up?

I know i would.

I'd solve the problem like this



for file in $1; do 
    if [ -f "$file" ]; then
        if [ $(((`date +%s` - `stat -L --format %Y $file`) > (172800))) -eq 1 ]; then
                today=$(date +"%Y%m%d")
                mkdir -p "$targetDirectory"
                mkdir -p "$targetDirectory/$today"
                mv $file "$targetDirectory/$today"
                echo "$file moved to $targetDirectory/$today/$file"

(The magic number 172800, is 2 days in seconds.)

Run the script like this: $ ./movebackup.sh "/Logfolder/*.log" Backups


Server.log moved to Backups/20160319/Server.log
Server17032016.log moved to Backups/20160319/Server17032016.log

And run that in a cronjob at midnight each day.

  • It's not kind of backup I just want to be move. So whatever date log file created I need to create directory of that date and need to be move file in that. – Chirag Dhaduk Mar 20 '16 at 3:50

OP is apparently expecting that a pathname like


is interpreted as if the last 8 digits in the filename are a date (day of month, month and year), and wants the directory name to be derived from that date.

A script for the given data might be like this:

find /Test1 -type f -mtime +2 | while IFS= read -r name
    date=$(echo "$name" | sed -e 's,^/Test1/Server,,' -e 's,\.log$,,' )
    [ -z "$date" ]          && continue
    [ "x$date" = "x$name" ] && continue
    mkdir -p /Test2/"$date"
    mv -f "$name" /Test2/"$date/"

although some refinement would be needed if the logfiles do not begin with the literal Server, as well as to exclude files which do not fit the pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.