0

I have a script I've been using to transcode videos from h264 to h265 in order to preserve space. A lot of manual effort is required to go through and delete the larger files (not always the h264 version). If I was able to determine whether or not FFmpeg finished successfully, I'd be able to save myself a lot of time.

I'll cut out a lot of stuff that's not relevant to the question but below you'll find my script.

function transcode() {
    output=$(echo "$1" | sed -r 's/^(.+)(\.\w{3})$/\1.h265\2/g');
    ffmpeg # a lot of options (including -hide_banner and -loglevel panic)
    echo "$output";
}

RESET=$(tput sgr0);
YELLOW=$(tput setaf 3);
CYAN=$(tput setaf 6);

for f in *.mp4; do
    original=$(stat -c %s "$f");
    echo "${YELLOW}Transcoding file: ${CYAN}$f${RESET}";
    new_file_name=$(transcode "$f");
    new_file_size=$(stat -c %s "$new_file_name");
    if [[ "$new_file_size" -gt "$original" ]]; then
        rm "$new_file_name";
    fi
    echo "";
done;

Ideally, I'd like to delete the original source file if the transcoded file is smaller and FFmpeg ran successfully. Unfortunately due to various reasons FFmpeg can fail while transcoding.

I have seen a few questions asking similar stuff but implementing it is just going over my head. I can't really be creating text files with the output either (though I guess that can be cleaned up as it goes).

Any help would be greatly appreciated.

Spedwards
  • 4,167
  • 16
  • 49
  • 106
  • See duplicate link, but instead of checking the exit code of parsing the resulting file, as shown in the link, you can check the exit code of the ffmpeg process. Also see example at the bottom of answer to [Bash script to recursive find and convert movies](https://stackoverflow.com/a/65635652/). – llogan Jan 31 '21 at 18:22
  • Instead of `sed` consider using [parameter expansion](https://mywiki.wooledge.org/BashFAQ/073). See simple example in [How do you convert an entire directory with ffmpeg?](https://stackoverflow.com/a/33766147/) – llogan Jan 31 '21 at 18:28

0 Answers0