Last active
September 30, 2018 20:25
-
-
Save taikedz/cac2559340e630629faf18d22a63ca2e to your computer and use it in GitHub Desktop.
Copy music files, in alphabetical order, to a new directory, converting non-mp3 files along the way
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
audio_file_extensions=(mp3 mp4 ogg oga ogv opus 3ga wav mka aiff mpeg mpg m4a wma wmv flac) | |
act() { | |
if [[ "${APPLY:-}" = true ]]; then | |
( set -x | |
# We don't want this command consuming the parent stdin | |
"$@" </dev/null | |
) | |
else | |
echo "$*" | |
fi | |
} | |
findfiles() { | |
local target extension | |
target="$1"; shift | |
for extension in "$@"; do | |
find "$target" -name "*.$extension" | |
done | |
} | |
main() { | |
dest="$1"; shift | |
IFS=$'\n\t' | |
songdirs=($(for x in "$@"; do echo "$x"; done|sort)) | |
IFS=$' \n\t' | |
for src in "${songdirs[@]}"; do | |
if [[ "${LIST:-}" = true ]]; then | |
echo "--> $src" | |
continue | |
fi | |
if [[ "$src" =~ (/\.\./|/\.\.$|^\.\./|^\.\.$) ]]; then | |
echo "ERROR --- '$src' cannot have '../' references in it" | |
exit 1 | |
fi | |
while read origin_file; do | |
mp3dir="$(dirname "$origin_file")" | |
[[ -d "$dest/$mp3dir" ]] || act mkdir -p "$dest/$mp3dir" | |
if [[ "$origin_file" =~ \.mp3$ ]]; then | |
destfile="$dest/$origin_file" | |
if [[ -f "$destfile" ]]; then | |
echo "SKIP: $destfile" | |
else | |
act cp "$origin_file" "$dest/$origin_file" | |
fi | |
else | |
new_file="${origin_file%%.*}.mp3" | |
destfile="$dest/$new_file" | |
if [[ -f "$destfile" ]]; then | |
echo "SKIP: $destfile" | |
else | |
act ffmpeg -loglevel -8 -nostats -i "$origin_file" "$destfile" | |
fi | |
fi | |
done < <(findfiles "$src" "${audio_file_extensions[@]}" | sort) # this stdin causes issues, hence above `</dev/null` | |
done | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment