0

I have a 1 TB HDD. And have problems copying data to it whenever i update it on my Ubuntu Machine.Can anybody suggest me how to make a script for Ubuntu such that whenever i mount it copy the newly dumped data from my PC HDD to my external HDD?

3
  • you mean one time once (after) it is mounted? Oct 12, 2014 at 20:17
  • yes i meant the same
    – kashminder
    Oct 14, 2014 at 8:02
  • perfect! I am glad it works Oct 14, 2014 at 8:22

1 Answer 1

1

You could use a script, running in the background, checking every (for example) 20 seconds if the disc is mounted. If it is, it runs an rsync job (once) to upload/update the files on the external disc.

The script below is an example, and so is the suggested rsync job. use man rsync for more information on rsync. It runs the backup job one single time after it is connected, waiting for the next time the disc is disconnected/connected, or when the script restarted.

How to use

  • Open the external disc or partition, right-click somewhere in the root directory of the disc and choose "properties" to see where the disc or partition is mounted (In the Location field of the nautilus properties window).
  • Copy the script below, paste it into an empty file and set the line:

    mounted_volume = "/mountpoint/of/the/disc"
    
  • Set the right paths in the lines:

    source_dir = "/path/to/source"
    target_dir = "/path/to/destination"
    

Save it as copy_ifconnected.py, run it by the command (and keep it running in the background):

python3 /path/to/copy_ifconnected.py

If it does what you want, add it to your startup applications.

The script

#!/usr/bin/env python3

import subprocess
import time

mounted_volume = "/mountpoint/of/the/disc"

source_dir = "/path/to/source"
target_dir = "/path/to/destination"

rsync = "rsync -r -t"

curr_status = False

def run_backup():
    rsync_job = rsync+" "+source_dir+" "+target_dir
    subprocess.Popen(["/bin/bash", "-c", rsync_job])

while True:
    connected = subprocess.check_output(["lsblk"]).decode("utf-8")
    test1 = mounted_volume in connected; test2 = curr_status==True
    if test1 != test2:
        if test1 == True:
            run_backup()
            curr_status = True
        else:
            curr_status = False
    time.sleep(20)
1
  • Can you also write a bash version for the same?
    – kashminder
    Oct 3, 2015 at 10:04

You must log in to answer this question.

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