Roelldev's Blog

Converting media in directory with Handbrake

Juli, 2020

Hello there,
Just a little script to convert multiple media files with handbrake. The script will process all files in the current directory by extension type and convert them to desired file type. Also the script will keep track of already processed files. I will use Ubuntu server to run the script.

Install

Dependencies to run the script.

Install handbrake-cli handbrake

sudo apt-get install handbrake-cli 

The Script

Create a file and edit it.

nano convert-media

#!/bin/bash
path=$1
srcExtension=$2
destExtension=$3

touch .processed-files

for file in `find $path -type f`; do # list all files in directory recursively
absoluteFilePath="$( cd "$(dirname "$file")" >/dev/null 2>&1 ; pwd -P )"/"$(basename $file )";
if [[ $file =~ \.$srcExtension$ ]]; then # check if file has required extension
    if ! grep -Fxq "$absoluteFilePath" .processed-files; then # check if file has been processed before
        newname=$(echo $file | rev | cut -f 2- -d '.' | rev) # get base path without file extension
        echo $newname;
        HandBrakeCLI -i "$file" -o "$newname.$destExtension"  # start converting file with handbrake
        echo "$absoluteFilePath" >> .processed-files;
    else
        echo "${file} already processed!";
    fi
fi
done;

Press ctrl + x then press y and enter to save your file.

Usage

Set execute permissions.

chmod +x convert-media

This will convert all files at the current directory with webm extension to mp4.

./convert-media . webm mp4

Will remove files with webm extension.

rm -r *.webm

If you want to reset the list of already processed files you can remove the file.

rm .processed-files

Source