Skip to content
Advertisement

How to move content of folder to unique folders every three hours in linux platform?

Whenvever my computer starts up I want to move contents of a folder to a unique folders.

For Example, Folder “A” has some Pictures then in the start up I want to MOVE the contents to a new folder “B”. Again after 3 Hours I want to Move the contents from Folder “A” to newly Created Folder “C”. Every Three hours I want a new folder to made for keeping the Content. Can any one help?

Advertisement

Answer

I created a script that creates backup accordingly to specified parameters. To add it to your system do following steps:

  1. You could save as something like folder_backup (don’t forget to make script executable by performing $ chmod +x folder_backup).
  2. (OPTIONAL step) After that you could copy it to /usr/local/bin if you want your script to be executable as command from any directory (sudo cp folder_backup /usr/local/bin).

Now you are ready to execute script with either typing $ ./folder_backup or $ folder_backup (if you copied / moved it to /usr/local/bin or other bin directory).

Usage: folder_backup FOLDER_NAME [BACKUP_FOLDER_NAME] (backup folder name is optional, if you won’t specify it will save backup at FOLDER_NAME_Year-Month-Day_Hour:Minutes.

Now that you have everything needed you just have to execute script in while or for loop for example: while true; do sleep TIME_IN_SECONDS; folder_backup FOLDER_NAME; done. This will create backup folders with timestamps if specified folder is not empty. For your specific case TIME_IN_SECONDS should be 10800, so command would look like while true; do sleep 10800; folder_backup A; done However you could write your own algorithm of backup folder naming and add it as second variable after name A. Also you should note that this won’t run in background, if you want it to run in background simply add & to end of while loop (after done).

Hope this is what you seek!!!

#!/bin/bash

create_backup () {
    # Check if 2 arguments are given to function.
    if [ -z ${3+x} ]; then
        # Check if folder from which we will make backup exists.
        if [ -d ${1} ]; then
            echo "Creating backup in ${2} of folder ${1}..."
            mkdir -p ${2}
            mv ${1}/* ${2}/
            echo "Backup stored in ${2}."
        else
            echo "There is no folder in ${1}!"
            exit 1
        fi
    else
        echo "You must specify folder and backup folder name!"
        exit 1
    fi
}

if [ -z ${2+x} ]; then
    # Only main folder specified
    main_folder=${1}
    date_stamp=`date +%Y-%m-%d_%H:%M`
    backup_folder=${main_folder}_"${date_stamp}
elif [ -z ${3+x} ]; then
    main_folder=${1}
    backup_folder=${2}
else
    echo "Specify folder path or folder name and backup folder path!"
    exit 1
fi

create_backup ${main_folder} ${backup_folder}
Advertisement