Script - Converting MKV Videos to MP4 Format (ffmpeg)

Script - Converting MKV Videos to MP4 Format (ffmpeg)

Ever needed to convert a collection of MKV video files to the more widely compatible MP4 format? Whether you’re preparing videos for streaming services or ensuring playback compatibility across devices, this bash script automates the conversion process using ffmpeg.

The Conversion Script

Here’s a practical bash script that handles MKV to MP4 conversion:

#!/bin/bash
# Check if ffmpeg is installed
if ! command -v ffmpeg &> /dev/null; then
echo "Error: ffmpeg is not installed"
exit 1
fi
# Create output directory if it doesn't exist
mkdir -p converted_videos
# Process all mkv files in current directory
for video in *.mkv; do
if [ -f "$video" ]; then
output_name="converted_videos/${video%.mkv}.mp4"
echo "Converting: $video to $output_name"
ffmpeg -i "$video" -codec copy "$output_name"
fi
done
echo "Conversion complete!"

How It Works

The script performs these key operations:

  • Verifies ffmpeg installation
  • Creates a ‘converted_videos’ directory for output files
  • Processes all .mkv files in the current directory
  • Maintains original video quality using stream copy

Usage Instructions

  1. Save the script as mkv2mp4.sh
  2. Make it executable:
Terminal window
chmod +x mkv2mp4.sh
  1. Run the script in your video directory:
Terminal window
./mkv2mp4.sh

Important Notes

  • The script uses -codec copy for fast conversion without re-encoding
  • Ensure enough disk space for output files
  • Original MKV files remain unchanged
  • Requires ffmpeg installation (sudo apt install ffmpeg on Ubuntu/Debian)

For custom video quality settings, modify the ffmpeg parameters. Example with re-encoding:

Terminal window
ffmpeg -i "$video" -c:v libx264 -crf 23 -c:a aac "$output_name"

This script provides a straightforward solution for batch converting MKV files to MP4, saving time on manual conversions.