Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question

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:

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?
    rm -rf "/disk2/data/${i}"                     # make sure target does not exist
    mv "${i}" "/disk2/data/${i}"                  # move stuff
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.

share|improve this answer
@slhck, nice one, looks good. Although whitespaces other than newlines shouldn't have been a problem with my version either. – MvG Aug 3 '12 at 9:49
Ah, should have worked, better be safe though :) – slhck Aug 3 '12 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 '12 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 '12 at 21:08

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.

share|improve this answer

You must log in to answer this question.

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