Find the answer to your Linux question:
Results 1 to 2 of 2
Hi all. New to Bash; writing a script to sync a flash drive with a folder on my hard drive. This is what I have so far: #!/bin/bash drive=CHARON usr=nicholas ...
  1. #1
    Just Joined!
    Join Date
    Nov 2008
    Posts
    4

    Syncing With a Flash Drive

    Hi all. New to Bash; writing a script to sync a flash drive with a folder on my hard drive. This is what I have so far:

    #!/bin/bash

    drive=CHARON
    usr=nicholas

    set -x

    #If the drive is not designed to sync (has no sync directory), the program quits.
    files=/media/$drive/sync/'*'

    #Create a corresponding sync folder on the main drive if necessary.
    mkdir -p /home/$usr/sync/$drive

    #Recursively delete all files in the base drive not in the external drive.
    cd; cd sync; cd $drive
    testFile=/media/$drive/sync
    function clean_up_wd
    {
    for f in `ls`
    do
    testFile="$testFile"/"$f"
    if [ ! -e "$testFile" ]
    then
    rm -r `pwd`/"$f"
    elif [ -d "$f" ]
    then
    cd "$f"
    clean_up_wd
    fi
    testFile=`dirname "$testFile"`
    done
    }
    clean_up_wd

    #Copy over all files on the external drive.
    for f in $files
    do
    cp -r $f /home/$usr/sync/$drive
    done

    The part that's giving me trouble is the clean_up_wd function---it doesn't behave like I want it to. It treats spaces as path separators, and while I usually avoid spaces, I can't promise myself that everyone else can--so what can I do to avoid that?

  2. #2
    Linux Guru
    Join Date
    Nov 2004
    Posts
    6,110
    I don't know if this will be good news or bad news, but there's a great program called rsync that will do what you're looking for with a lot less effort. It has all sorts of great options for tweaking the sync to your needs.
    Code:
    rsync -uav --delete $f /home/$user/sync/$drive
    Of course until this is behaving the way you want it to you might want to exclude the --delete switch

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...