Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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.

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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