Difference between revisions of "Bi-Directional Directory Synchronization"

From TheBeard Science Project Wiki
Jump to: navigation, search
(Created page with " <source lang="sh"> #!/bin/bash # # Bi-directional synchronization between folders. Always keep the most recent version of files. # # The synclist is an array of strings,...")
 
 
Line 1: Line 1:
  
 +
Requires <code>rsync</code>:
 +
<source>sudo apt-get install rsync</source>
  
 +
Custom script <code>sync-directories.sh</code>:
 
<source lang="sh">
 
<source lang="sh">
  
Line 14: Line 17:
  
 
synclist=(\
 
synclist=(\
   "/home/user/Documents/Personal Documents/Recipes/|/shares/Public/Recipes/"\
+
   "/home/user/Documents/Personal Documents/Recipes/|/shares/Public/Recipes/" \
   "/home/user/Documents/Workfiles/|/shares/Private/Work/"\
+
   "/home/user/Documents/Workfiles/|/shares/Private/Work/" \
 
   )
 
   )
  

Latest revision as of 16:21, 24 December 2019

Requires rsync:

sudo apt-get install rsync

Custom script sync-directories.sh:

#!/bin/bash
#
# Bi-directional synchronization between folders. Always keep the most recent version of files.
#
#   The synclist is an array of strings, each string is a pipe-delimited pair of directories.
#   Each directory MUST have the "/" at the end of it, otherwise it will create new folders.
#   Spaces are okay as long as the string is quoted.
#   Example: "/dir1/|/dir2/"
#

synclist=(\
  "/home/user/Documents/Personal Documents/Recipes/|/shares/Public/Recipes/" \
  "/home/user/Documents/Workfiles/|/shares/Private/Work/" \
  )

logfile="/logs/sync-directories.log"

s=$IFS
IFS=$(echo -en "\n\b")
for pair in ${synclist[@]};do
  dir1=$(echo $pair|awk -F"|" '{print $1}')
  dir2=$(echo $pair|awk -F"|" '{print $2}')
  stat="FAILED"
  if [[ -d "$dir1" ]] && [[ -d "$dir2" ]];then
    echo -e "\nSYNC : $dir1 <--> $dir2"
    rsync -rptuv "$dir1" "$dir2"
    result1=$?
    echo -e "\nSYNC : $dir2 <--> $dir1"
    rsync -rptuv "$dir2" "$dir1"
    result2=$?
    if [[ $result1 ]] && [[ $result2 ]];then
      stat="SUCCESS"
    fi
  fi
  echo "[$(date)] $stat : $dir1 <--> $dir2" >>$logfile
done
IFS=$s