Skip to content

Instantly share code, notes, and snippets.

@kayhadrin
Last active January 12, 2023 04:38
Show Gist options
  • Save kayhadrin/ad27b394ec2d104727fd53a2cd705b53 to your computer and use it in GitHub Desktop.
Save kayhadrin/ad27b394ec2d104727fd53a2cd705b53 to your computer and use it in GitHub Desktop.
Syncthing: bash script to move the latest version of all files from a given folder to a target folder

Syncthing: script to MOVE the latest version of all files from a given folder to a target folder

This is useful in case you've mistakenly deleted a very large folder and it takes forever to restore the files via "file copy". In this case, we're literally MOVING the old version files to the target location! So be careful, this cannot be reverted!

Usage:

./syncthing-restore-version.sh srcFolder dstFolder

Example:

./syncthing-restore-version.sh "My Pictures/.stversions" "My Pictures/restored versions"

NOTE: you should run this script as the "sc-syncthing" user to avoid file permission issues (See runAsSyncthing.sh)

#!/bin/bash
# Script to run a given bash command as another user hard-coded to "sc-syncthing"
args=''
for arg in "$@"; do
args="$args $(printf %q "$arg")"
done
sudo su -s /bin/bash -c "$(printf %q "$args" | xargs)" sc-syncthing
#!/bin/bash
# Syncthing: script to MOVE the latest version of all files from a given folder to a target folder
# This is useful in case you've mistakenly deleted a very large folder and it takes forever to restore
# the files via "file copy".
# In this case, we're literally MOVING the old version files to the target location!
# So be careful, this cannot be reverted!
#
# Usage: scriptName srcFolder dstFolder
# Example:
# ./syncthing-restore-version.sh "My Pictures/.stversions" "My Pictures/restored versions"
#
# NOTE: you should run this script as the "sc-syncthing" user to avoid file permission issues (See runAsSyncthing.sh)
srcPath="$1"
dstPath="$2"
echo srcPath=$srcPath
echo dstPath=$dstPath
relPathToDst=$(realpath "--relative-to=$srcPath" "$dstPath")
echo relPathToDst=$relPathToDst
cd "$srcPath"
# Find versioned files and list them in reverse order so that the latest versions appear first
find -O3 . -type f -regextype posix-awk -regex '.*~[0-9]{8}-[0-9]{6}.*$' | \
sort -r |
while read -r srcFile; do
# strip version suffix from filename
targetFile=$(echo $srcFile | sed -r 's/(.*)~[0-9]{8}-[0-9]{6}(\.[^~]+)?$/\1\2/g')
targetFile="$relPathToDst/$targetFile"
echo Source file: "$srcFile", Target file: "$targetFile"
if [[ -f "$targetFile" ]]
then
echo File already exists! target="$targetFile"
else
mkdir -p "$(dirname "$targetFile")" && mv -n "$srcFile" "$targetFile"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment