Running ffmpeg in loop seems to change reading from file

Hi everyone,

I am fairly new to shell scripting. I want to read in numbers from a file (one number per line). This works perfectly fine

  
while read CurrentLine
do
echo $CurrentLine
done < myfile 

and yields the correct output:

 
272
745
123

If I however run a ffmpeg command in the loop

  
while read CurrentLine
do
echo $CurrentLine
ffmpeg -sameq -vframes 1 -ss 2 -i PMI_thin_02.avi -f image2  a_b.png
done < myfile 

the output changes (I ommit the ffmpeg output and just give the echo command output):

 
272
5
3

If I add two spaces in the txt-file I read in, such as

 
272
  745
  123

the echo command returns the right numbers again - for some reason, the ffmpeg commands seems to result in the skipping of the first two characters in the new line.
If I put an additional for-loop around the while loop to loop over several files such as in

 
for FileName in *.txt; do
	while read CurrentLine
	do
	echo $CurrentLine
ffmpeg -sameq -vframes 1 -ss 2 -i PMI_thin_02.avi -f image2  a_b.png
	done < "${FileName}"

The first line of every file is read in correctly, but for all subsequent lines, the first two characters are skipped. Does anybody have any idea what is going on? I am very grateful for any hint.

Best,
Thriceguy

My guess is that ffmpeg is reading two bytes from stdin. If you are using, or can use, kshell, then you can avoid that with code like this:

#!/bin/ksh

exec {fd}<data-file      # open the file assign file descriptor to fd
while read -u $fd buf   # read from fd rather than stdin
do
    echo $buf
    #ffmpeg-command and parms
done
<&$fd-      # close the file

The while reads from the file descriptor opened by the exec statement and assigned to fd and thus isn't affected by what anything in the loop might read from stdin.

If you need to, or would rather use bash, then you'll have to specifically pick a file descriptor to use:

fd=11
exec 11<data-file        # open the file assign file descriptor to fd
while read -u $fd buf   # read from fd rather than stdin
do
    echo "$buf $foo"
    ffmpeg-command here
done
<&$fd-      # close the file

And, from my small bit of testing, you have to supply a hard number on the exec when using bash, this seems not to work: exec $fd<data-file

---------- Post updated at 13:04 ---------- Previous update was at 12:58 ----------

Kludgy, but this would work allowing the variable contents to be used when opening:

fd=9
eval exec $fd\<data-file
1 Like

Thanks a lot, it works perfectly.

Best,
Thriceguy