Not sure I like that nested while loop that takes input from the < after the block, at least I find it hard to read.
the script below, attempts to break this down to a single find loop, where we pipe its output into a while.
I additionally separated the iterate over directory part from the do operation part, so as to allow the iterate over directories with spaces logic to be reused.
Note the use of quotes everywhere. I also like to surround all variables with { } and end lines with ; , but that's just a preference thing.
Code:
#!/bin/bash
root_dir="$(pwd)";
if [ -z "${1}" ]; then
echo "Using current directory as base for scanning.";
else
root_dir="${1}";
fi
if [ ! -d "${root_dir}" ]; then
echo "Failed to find directory: ${root_dir}"
exit 1;
fi
echo "Current Root Path: ${root_dir}";
# converts a single m4a file to a mp3 file
# storing the converted file in the same folder as the original
# but only if there does not already exist the output mp3 file
#
# parameter1: full path to the .m4a file
function convert_mp3() {
in_file="${1}";
parent_dir="$(dirname "${in_file}")";
file_name="$(basename "${in_file}")";
mp3_file="$(echo "${file_name}" | sed -e "s/\.m4a$/.mp3/")";
out_file="${parent_dir}/${mp3_file}";
if [ -f "${out_file}" ]; then
echo "skipping already converted file ${in_file}, target .mp3 exists.";
else
faad -q -o - "${in_file}" | lame -h - "${out_file}" &> /dev/null;
if [ $? -ne 0 ]; then
echo "ERROR: Failed to execute convert ${in_file}, see above for more Details."
exit 1;
fi
echo "converted ${in_file} => ${out_file}";
fi;
}
# find all *.m4a files and calls the function to convert them to mp3 files
# works when the directories and/or files have spaces in them.
find "${root_dir}" -type f -name "*.m4a" | while read a_file; do
echo "${a_file}";
convert_mp3 "${a_file}";
done;