Search code examples
bashshellcron-task

BASH script to copy random directory contents to another location


The title pretty much says it all. What i am trying to accomplish is the following,

I have 12 Directories each which will contain 12 files. I want to create a script that will run everyday at midnight, at that time it needs to randomly select one of the 12 directories and copy all 12 files in that directory to another location. It will also need to delete any files in the destination directory before it copies the new files over.

Thanks,

Heinrich


Solution

  • crontab entry (run at midnight)

    0 0 * * * /tmp/myscript.bash
    

    Here's the contents of /tmp/myscript.bash:

    #!/bin/bash
    #Destination directory
    destDir=/mnt/stuff/someDir
    
    #a randomly chosen directory name
    #Dirs to copy from are named dir0,dir1,dir2,dir3,dir4,dir5,dir6,dir7,dir8,dir9,dir10,dir11
    dirName=dir$(($RANDOM%12))
    #You can add a case statement to set a different name
    # based on the number that's chosen in case you already
    # had 12 dirs with names other than the integers I've listed.
    
    #Clear out the existing files from the destination dir
    rm "${destDir}"/*
    
    #move the files from the 'random' directory to the destination
    mv "${dirName}"/* "${destDir}"
    

    (I would suggest storing the script somewhere other than /tmp)