#!/bin/bash
# randtracks
# Copy a random collection of songs from source to dest.
# Do not use ~ for these (TODO fix this)
sourced="/home/paul/music"
destd="/media/usbdisk/music"
index=~/MusicIndex
index_done=~/MusicIndexDone
function ErrorExit()
{
echo "Error: $*" >&2
exit 1
}
function Dbg
{
echo "[D] $*" >&2
}
# Make sure the source and directories exist
if [ ! -d "$sourced" ]; then
ErrorExit "Could not find source directory $sourced"
fi
if [ ! -d "$destd" ]; then
ErrorExit "Could not find destination directory $destd"
fi
if [ ! -e $index ]; then
echo "Creating index $index"
find "$sourced" -type f -name '*.mp3' -o -name '*.ogg' > "$index"
fi
track_count=$(wc -l < "$index")
echo "Have $track_count tracks in the collection"
# Now randomly pick tracks to be copied
max_loop=$(($track_count * 2))
for((i=0; i < $max_loop && $track_count > 0; i++))
do
line_num=$(($RANDOM%$track_count+1))
# Pick a line at random out of the index
src_this=$(sed -n "$line_num p" < "$index")
Dbg "Have chosen line $line_num/$track_count, Src=$src_this"
# Format up the destination path
destf="${destd}${src_this#$sourced}"
#Dbg "From : $src_this"
#Dbg "To : $destf"
# Try and create the dest directory
mkdir -p "$(dirname "$destf")"
if [ -e "$destf" ]; then
echo "$destf already exists, skipping"
# Maybe stop processing at this point
elif cp -v "$src_this" "$destf" ; then
Dbg "Removing line $line_num from $index"
# Remove the line from the index
if ! (sed "$line_num d" < "$index" > "$index.tmp" && mv "$index.tmp" "$index") ; then
ErrorExit "Removing line $line_num from $index"
fi
# Write the line we have randomly picked to another file for reference
# This is not needed
echo "$src_this" >> "$index_done"
# adjust counts
track_count=$(($track_count - 1))
else
Dbg "Failed to copy, exiting"
break
fi
done
Bookmarks