3

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?

2
  • What about using absolute paths instead of relative ones? For instance: /tmp/rootarchive/"$file" Regards Nov 15, 2015 at 21:29
  • 1
    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.
    – kos
    Nov 16, 2015 at 11:43

1 Answer 1

8

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.
1
  • Thx for your help worked perfectly fine!
    – user472513
    Nov 19, 2015 at 19:04

You must log in to answer this question.