I'm working on a script for screen recording using FFmpeg, and I need a way to automatically name the output files incrementally (e.g., out1.mp4, out2.mp4, etc.), while ensuring that any existing files are skipped. I've thought of a few methods but they all seem overly complicated. Does anyone have a simpler solution?
4 Answers
Using epoch time is another straightforward option: `out_$(date +%s)`. This way, you'll never have a filename collision.
You could also use a while loop to create your files incrementally. Something like: `i=1; while [[ -f out$i.mp4 ]]; do i=$((i + 1)); done; ffmpeg ... "out$i.mp4"` to ensure you don’t overwrite any existing files.
This method you shared is pretty solid—short and straightforward! Just to confirm, this will indeed avoid writing over existing files? I’m just making sure because that’s been my main concern!
Yes, it will skip existing files. That's the beauty of using this loop! You won't overwrite anything.
Instead of using loops, you could simply use a timestamp in your output filename. For example, try this command: `ffmpeg -i [input] "out_$(date +%Y%m%d_%H%M%S).mp4"`. It will give you a unique name every time you record!
This is a great method! I recommend using `+%F` instead of `+%Y%m%d` to make it easier to type, plus you could use `+%T` if you want the time too!
I hadn't considered that! Thanks for the suggestion. It sounds much simpler.

Thanks! I assume this will skip any existing files? Like if out1.mp4 is there, it would go to out2.mp4 instead? I'm still a bit new to this.