Skip to content

Instantly share code, notes, and snippets.

@sharmashivanand
Last active April 24, 2022 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharmashivanand/a4309e10a9e474393d46ed205ecb59cd to your computer and use it in GitHub Desktop.
Save sharmashivanand/a4309e10a9e474393d46ed205ecb59cd to your computer and use it in GitHub Desktop.
#!/bin/bash
# This copies files from a source folder into a destination. Date-based subfolders are created and files are copied into them.
# The Sony RX1 MTP disconnected frequently so I had to build this script to copy photographs into destination organized by date-based subfolders.
# The date is detected by the output of file modification time $(date -r).
# This script hasn't been tested with paths containing spaces or special characters. Use at your own risk!
confirm() {
# call with a prompt string or use a default
read -r -p "${1:-Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
true
;;
*)
false
;;
esac
}
echo
echo "Are you running it as ./sd-to-mtp-copy.sh $1 $2 2>&1 | tee copying-\$(date +%s).log"
confirm "Continue? [y/N]"
echo
if [[ -z $1 || ! -d $1 ]];
then echo "Source path not specified or is unreachable. Aborting!"
exit 1
fi
if [[ -z $2 || ! -d $2 ]];
then echo "Destination path not specified or is unreachable. Aborting!"
exit 1
fi
if ! command -v exiftool &> /dev/null
then
$'exiftool could not be found.\nIt\'s best to install it for reliably detecting the dates.\nWe\'ll have to rely on last modification time of files \n :( :( :('
et=0
else
et=1
fi
#echo "Source path $1"
#echo "Destination path $2"
src=$(realpath "$1")
dest=$(realpath "$2")
[[ ${src: -1} != "/" ]] && src="$src/"; :
[[ ${dest: -1} != "/" ]] && dest="$dest/"; :
echo "Source path: $src"
echo "Destination path: $dest"
#files=$(find $src -type f)
#echo $files
shopt -s globstar
for x in $src**; do
if [[ -f $x ]]; then
#echo $x
# Let's just use a temporary variable in case if we need to alter it somehow somewhere etc.
y="$x"
if [ "$et" -eq "1" ]; then
d=$(exiftool -d "%s" -DateTimeOriginal "$y" | grep -oP '\d+')
if [ ! -z "$d" ]; then
d=$(date -d @$d +%Y-%m-%d)
else
echo "Warning: Could not detect date from exif data. Using File Modification Time for $x"
d=$(date -r "$y" +%Y-%m-%d)
fi
else
d=$(date -r "$y" +%Y-%m-%d)
fi
echo "Log: $x -> $dest$d/$(basename "$y")"
mkdir -vp "$dest$d"
cp -vn "$y" "$dest$d/"
fi
done
echo ""
echo "All done! Files copied to $dest. Existing files were skipped."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment