'How to concatenate variables and strings as a full path for the "output file" of an ffmpeg command in a bash script

I'm trying to learn to bash scripting and I tried to use variables and arguments, etc. to specify a complex output file name to a ffmpeg command as follows :

for file in "$1"/*; do
    #get the name of each file in the directory (without the path nor the extension)
    filename=$(basename $file .mp3)
    #use mimic for Text To Speech. Difficult to install but good and natural voices.
    ~/Desktop/mimic1/mimic -t "$filename" -o $1/wavefile.wav
    #converts the wav file outputed by mimic into mp3
    ffmpeg -i $1/wavefile.wav -f mp3 "${1}/${filename} (title).mp3"
done

But the "${1}/${filename} (title).mp3" part in particular really doesn't seem to work...

Indeed, if I run script.sh ./, I get a file called (title).mp3

Can you help me figure out what it is I'm doing wrong ? Thanks a million in advance. Best,

P.S. : i also get earlier in the terminal's output basename: extra operand ‘.mp3’...like my whole code is wrong....?



Solution 1:[1]

I'm guessing you're possibly getting hung up on directory paths or filenames with spaces. To fix this, you just need to use double-quotes around any variables that reference a dir/file with a potential space.

In addition, I'm guessing your basename binary doesn't support specifying an extension to remove. If you're on a mac, use homebrew to install the coreutils to get a good version. Or, you can use bash variable substitution to strip off the extension as shown below.

for file in "$1"/*; do
    #get the name of each file in the directory (without the path nor the extension)
    filename="$(basename -- ${file%.*})"
    #use mimic for Text To Speech. Difficult to install but good and natural voices.
    ~/Desktop/mimic1/mimic -t "$filename" -o "$1/wavefile.wav"
    #converts the wav file outputed by mimic into mp3
    ffmpeg -i "$1/wavefile.wav" -f mp3 "${1}/${filename} (title).mp3"
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dean Householder