execute ffmpeg command in a loop

2019-01-19 01:23发布

问题:

I have 3 .wav files in my folder and I want to convert them into .mp3 with ffmpeg I wrote this bash script that will come as follow, but when I execute it, only the first one will have been converted to mp3 what should I do to make script keep going through out of my files

this is the script :

#!/bin/bash
find ./ -name "*.wav" -print | while read f
do
    name=${f:2:${#f}-6}
    cmd='ffmpeg -i "$name.wav" -ab 320k -ac 2 "$name.mp3"'
    eval $cmd<br>
done

回答1:

No reason for find, just use bash wildcard globbing

#!/bin/bash
for name in *.wav; do
  ffmpeg -i "$name" -ab 320k -ac 2 "${name%.*}.mp3" 
done 


回答2:

Use the -nostdin flag in the ffmpeg command line

ffmpeg -nostdin -i "$name.wav" -ab 320k -ac 2 "$name.mp3"


回答3:

If you do need find (for looking in subdirectories or performing more advanced filtering), try this:

find ./ -name "*.wav" -exec ffmpeg -i "{}" -ab 320k -ac 2 '$(basename {} wav)'.mp3 \;

Piping the output of find to the while loop has two drawbacks:

  1. It fails in the (probably rare) situation where a matched filename contains a newline character.
  2. ffmpeg, for some reason unknown to me, will read from standard input, which interferes with the read command. This is easy to fix, by simply redirecting standard input from /dev/null, i.e. find ... | while read f; do ffmpeg ... < /dev/null; done.

In any case, don't store commands in variable names and evaluate them using eval. It's dangerous and a bad habit to get into. Use a shell function if you really need to factor out the actual command line.



标签: bash ffmpeg