Script for moving files that are older than 5 days

7,832

You need to create the directory tree from subdir1/subdir2/ - mv won't do that for you. You could do, for example:

find . -type f -mtime +5 -print0 | while IFS= read -r -d '' file; do
    dir="${file%/*}"
    mkdir -p ../rootarchive/"$dir"
    mv "$file" ../rootarchive/"$file"
done

You could rsync. It can recreate the directory structure and do deleting copied files:

find . -type f -mtime +5 -print0 | 
  rsync -0avP  --remove-source-files --files-from=- ./ ../rootarchive

For rsync:

  • -0 indicates file lists are null-separated. This affects:
  • --files-from= reads the list of files to be copied (from stdin: -).
  • -a enables archive mode, which retains file permissions, ownership, etc.
  • --remove-source-files deletes files which have been copied successfully from the source.
  • -vP enable verbose mode and progress information.
Share:
7,832

Related videos on Youtube

muru
Author by

muru

Updated on September 18, 2022

Comments

  • muru
    muru over 1 year

    I'm currently working on a script that allows me to move any file thats older than 5 days into an archive folder with the same path, except for the root folder which changes. So something like: root/subdir1/subdir2/file to rootarchive/subdir1/subdir2/file. It should work recursivly.

    I've already tried creating a foreach for all the files of the "root" folder:

    #!/bin/bash
    find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
          mv $file ../rootarchive/"$file"
    done
    

    But this didn't work properly as I the mv command couldnt find the specified destination ../rootarchive/"$file". Has anyone of you an idea how I could solve this problem?

    • Eduardo López
      Eduardo López over 8 years
      What about using absolute paths instead of relative ones? For instance: /tmp/rootarchive/"$file" Regards
    • kos
      kos over 8 years
      The kernel doesn't support providing informations about the creation time of a file, so if you need to move files older than X you'll have to work out a way to to do the check using debugfs.
  • Admin
    Admin over 8 years
    Thx for your help worked perfectly fine!