The original problem
This may be more of a bc
or bash
question than an FFmpeg one, although I would also appreciate being able to prevent ffprobe
from printing carriage returns after its output.
In a script I'm writing to automate some common tasks with FFmpeg, I'm getting the length of two files using the following:
length1="$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"$1\")"
length2="$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 outro.mp4)"
read -p "Enter the desired duration of the fade in seconds: " fadeduration
...which outputs successfully as:
$ echo $length1; echo $length2
177.800000
10.567000
<USER INPUT; usually a 2 followed by ENTER>
However, attempting to perform basic calculations on these variables with bc:
total=$(echo "$length1 +$length2" - "$fadeduration" | bc)
echo $total
...results in an empty variable.
Troubleshooting process
I tried to break the command down into simpler parts, and even this failed:
$ echo "$length1 + $length2" | bc
(standard_in) 1: illegal character: ^M
(standard_in) 1: illegal character: ^M
This was because, for some reason, the ffprobe
commands (at least in my MSYS2-built binary) add a Windows line ending to the end of the output, and therefore the variables.
I fixed this problem by piping the output through tr
to strip it of carriage returns:
echo "$length1 + $length2" | tr -d $'\r' | bc
The current problem
But doing the same thing with my original calculation still doesn't work:
$ echo "$length1 + $length2 - $fadeduration" | tr -d $'\r' | bc
(standard_in) 2: syntax error
This time bc
returns a syntax error, suggesting that a) I'm getting somewhere, and b) it's a problem with how I've written it.
How can I do this calculation in bc
so that it successfully populates my variable?
Posting in line the output as seen by od -c
$ echo "$length1 + $length2 - $fadeduration" | od -c
0000000 1 7 7 . 8 0 0 0 0 0 \r + 1 0
0000020 . 5 6 7 0 0 0 \r - \n
cat -vet
which shows all the special characters, with$
at the end.bc
. Why else would a variable fail to set? `fadeduration
in the question but it comes from user input:read -p "Enter the desired duration of the fade in seconds: " fadeduration
. For these tests I've been typing the value 2 and pressing Enter.read
and therefore assumed the hypothesis from my first comment (now deleted) was wrong. Now I see$fadeduration
expands to an empty string. What is the question not telling us? Do you runread
in a subshell maybe?$fadeduration
seemed to retain its value when echoed out before the FFmpeg command - all variables except$total
did.