1

I'm using the following line to convert

for f in *.mkv; do ffmpeg -i "$f" -c:v copy -c:a aac -b:a 256k "${f%%mkv}mp4";&& rm "{$f}.mkv"; done

i need this to also check sub directories but i keep getting token error or bash error

also it doesn't delete the mkv files when finished converting

once i have the line working correctly how would i then go one step further and make it auto run say once a day to convert any newly added mkv files.

muru
  • 197,895
  • 55
  • 485
  • 740
playl01
  • 29

1 Answers1

7

ffmpeg -i "$f" -c:v copy -c:a aac -b:a 256k "${f%%mkv}mp4";&& rm "{$f}.mkv"; is a syntax error - you cannot have a && after a ;. It should just be ffmpeg -i "$f" -c:v copy -c:a aac -b:a 256k "${f%%mkv}mp4" && rm "{$f}.mkv";. Then, your $f already ends in .mkv, so the rm command should be just rm "$f".

To recurse into subdirectories, use globstar:

shopt -s  globstar
for f in **/*.mkv; do ... done

All told:

#! /bin/bash
shopt -s  globstar
for f in **/*.mkv
do
  ffmpeg -i "$f" -c:v copy -c:a aac -b:a 256k "${f%%mkv}mp4" &&
    rm "$f"
done

To run it on a schedule, see Running a script everyday using a cronjob or How do I properly install a systemd timer and service?.

muru
  • 197,895
  • 55
  • 485
  • 740
  • Hi thank you for the answer I’ve been pulling my hair out so if I want it to run say all sun directories or /storage2/ do I just add that instead of the ** in front of mkv – playl01 Oct 22 '21 at 18:18
  • So basically all the sub directories under storage2/Series. Have mkv files in – playl01 Oct 22 '21 at 18:35
  • When I run this it says no mkv file found, it’s not searching sub directory – playl01 Oct 23 '21 at 23:30
  • @playl01 What exactly did you run? If you want to use it in /storage2, either cd there before running this, or replace **/*.mkv with /storage2/**/*.mkv. – muru Oct 24 '21 at 15:20
  • */.mkv no suck file directory so the mkv are all in sub directories of storage2 – playl01 Oct 24 '21 at 21:35
  • Hi so within series./ we have sub folders 2 deep when I run the above script it is saying no such file or directy – playl01 Oct 25 '21 at 09:09