#!/bin/env bash # Craig Jennings # convenience utility to convert all media files not in opus format in current directory to opus. # flags for recursive or specific filename supported. # Default values of arguments delete_after_conversion=false filename="" recursive=false # Usage info show_help() { cat << EOF Usage: ${0##*/} [-h] [-d] [-r] [-f FILE] Convert audio/video files to the Opus format. -h display this help and exit -d delete source files after conversion -r convert files recursively in current and subdirectories -f FILE convert a specific file. Note: The '-f' and '-r' options are mutually exclusive. If no file is given, works on all non-opus media files in the current directory. Requires the ffmpeg installation. EOF } # Check for the existence of ffmpeg if ! command -v ffmpeg &> /dev/null; then echo "Cannot proceed: ffmpeg not found on path." exit 1 fi # Identify arguments; quit if invalid argument while getopts ":df:rh" opt; do case ${opt} in d) delete_after_conversion=true ;; f) filename=$OPTARG ;; r) recursive=true ;; h) show_help exit 0 ;; \?) echo "Invalid option: -$OPTARG" >&2 show_help exit 1 ;; esac done # Display error and quit if incompatible arguments if [ "$recursive" = true ] && [ -n "$filename" ] then echo "The -f and -r options cannot be used together." show_help exit 1 fi # Convert function checks mime-type and converts/deletes a single file convert() { f=$1 # Check the mime-type of the file mime_type=$(file -b --mime-type "$f") # If the file is an audio or video file and not already in opus format then convert it to opus if [[ $mime_type == video/* || $mime_type == audio/* ]] && [[ $f != *.opus ]]; then ffmpeg -i "$f" "${f%.*}.opus" # If the '-d' option was specified, delete the original file after conversion if $delete_after_conversion; then rm "$f" fi fi } # Use above convert function based on user's intended set of files if [ "$recursive" = true ] then # convert all media files in current and child directories find . -type f -exec bash -c 'convert "$0"' {} \; elif [[ -n $filename ]] then # if filename is not empty, convert only this file convert $filename else # Convert all echo "All non-opus media files in the current directory will be converted. Originals are kept." read -p "Proceed? (Y/n) " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]] then # Iterate over each file in the directory and convert for f in *; do convert $f done fi fi