Skip to content

Instantly share code, notes, and snippets.

@Schievel1
Created November 22, 2023 21:26
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 Schievel1/56f28493f9aa03ee377b27987a76db38 to your computer and use it in GitHub Desktop.
Save Schievel1/56f28493f9aa03ee377b27987a76db38 to your computer and use it in GitHub Desktop.
sync music folders and convert while at it...
#!/usr/bin/env bash
set -e # exit script if control-c is used
main() {
USAGE="Usage: $0 source_dir destination_dir ffmpegcommand"
if [ $# != 3 ] ; then
echo $USAGE
exit 1;
fi
# Convert relative path to absolute. Also remove trailing slash
SOURCE_DIR="$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
SOURCE_DIR=$(dirname "$SOURCE_DIR/temp") # this fixes . and ./
DESTINATION_DIR="$(cd "$(dirname "$2")"; pwd)/$(basename "$2")"
DESTINATION_DIR=$(dirname "$DESTINATION_DIR/temp") # this fixes . and ./
# sync files and convert to mp3 if they dont exist as mp3 in destination yet
find "$SOURCE_DIR" \( -iname '*.flac' -or -iname '*.m4a' \) -type f -print | while read -r FILE
do
ORIG_DIR=$(dirname "$FILE")
# Get basename and remove extension
BASE=$(basename "$FILE") # get filename
BASE=${BASE%.*} # remove extension from filename
NEW_DIR=${ORIG_DIR/$SOURCE_DIR/$DESTINATION_DIR}
mkdir -p "$NEW_DIR"
NEW_FILE="$NEW_DIR/$BASE.mp3"
if [ ! -f "$NEW_FILE" ]; then
echo "Converting $FILE to $NEW_FILE"
# </dev/null added so ffmpeg doesn&#39;t read input
$3 -hide_banner -i "$FILE" -c:a libmp3lame -q:a 2 "$NEW_FILE" </dev/null # standard mp3
fi
done
# delete files from destination if they they don't exist in source anymore
find "$DESTINATION_DIR" -type f -print | while read -r DESTFILE
do
echo "destfile " $(basename $DESTFILE)
DELETE=true;
find "$SOURCE_DIR" -type f -print | while read -r SOURCEFILE
do
echo " sourcefile "$(basename $SOURCEFILE)
if [[ $(basename ${DESTFILE%.*}) == $(basename ${SOURCEFILE%.*}) ]]; then
echo " found matching source file, don't delete"
DELETE=false
break
fi
done
if [[ DELETE == true ]]; then
echo " could not find a matching source file for $DESTFILE, deleting"
rm $DESTFILE
fi
done
echo "syncing directory structure of $SOURCE_DIR to $DESTINATION_DIR"
# NOTE This deletes even non empty directories in destination if they don't exit in source anymore
rsync -av --delete-excluded --force --ignore-existing --include='*/' --exclude='*' "$SOURCE_DIR/" $DESTINATION_DIR
echo "syncing all files from $SOURCE_DIR to $DESTINATION_DIR except .flac and .m4a files"
rsync -av --ignore-existing --exclude='*.flac' --exclude='*.m4a' "$SOURCE_DIR/" $DESTINATION_DIR
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment