0

Well, what I want to do is

  1. The cron should run every hour or so
  2. It should move the directories in a folder /disk1/data/ older than 24 hours to /disk2/data/
  3. The directories moved should contain all the data (files/folders) inside of them

I'm a beginner at cron jobs so I have absolutely no idea where to start. Thanks for any help!

2 Answers 2

1

What exactly do you mean by the age of a directory? Time since the creation of its inode? I suggest you use find to identify the directories you want to move. E.g. like this:

#!/bin/bash
res=0
cd /disk1/data/
find -type d -ctime +1 -print0 -prune | \
while IFS= read -r -d '' i; do
    if [[ ${i} == */* ]]; then                    # need to ensure subdir exists
        if ! mkdir -p "/disk2/data/${i%/*}; then  # error creating dir?
            res=1
            continue
        fi
    fi
    rm -rf "/disk2/data/${i}"                     # make sure target does not exist
    mv "${i}" "/disk2/data/${i}"                  # move stuff
done
exit ${res}

If other people were allowed to write disk2, then this code might be vulnerable to some kinds of symlink attacks if someone creates the right symlinks fast enough. Not sure.

I suggest you write the script to some file and execute that from the cronjob. You create a conjob with crontab -e (make sure you've set your EDITOR environment variable appropriately), following the format described in man crontab.

4
  • @slhck, nice one, looks good. Although whitespaces other than newlines shouldn't have been a problem with my version either.
    – MvG
    Aug 3, 2012 at 9:49
  • Ah, should have worked, better be safe though :)
    – slhck
    Aug 3, 2012 at 9:57
  • Hey, I'm getting an error when running it, "read: 13: Illegal option -d" How do I fix this?
    – yashau
    Aug 4, 2012 at 18:16
  • If the read builtin of your bash doesn't support the -d option yet, you could omit both the IFS= and the -d '', use -print instead of -print0, and hope that noone in his right mind will use a file name containing a newline character. Now that I think of it, this might be due to the fact that bash is executed as sh i.e. in compatibility mode. I'll edit the answer, make sure to include the first line.
    – MvG
    Aug 4, 2012 at 21:08
0

Note that the -ctime option of find does not mean creation time but "inode change time". The field st_ctime is changed by writing or by setting inode information (owner, group, link count, mode, etc.). For directories, it will also reflect the last time a file (or subdirectory) was created or deleted in that directory. So, consider whether find -type d -ctime +1 is really the option you require.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .