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 installedif ! command -v ffmpeg &> /dev/null; then echo "Error: ffmpeg is not installed" exit 1fi
# Create output directory if it doesn't existmkdir -p converted_videos
# Process all mkv files in current directoryfor 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" fidone
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
- Save the script as
mkv2mp4.sh - Make it executable:
chmod +x mkv2mp4.sh- Run the script in your video directory:
./mkv2mp4.shImportant Notes
- The script uses
-codec copyfor fast conversion without re-encoding - Ensure enough disk space for output files
- Original MKV files remain unchanged
- Requires ffmpeg installation (
sudo apt install ffmpegon Ubuntu/Debian)
For custom video quality settings, modify the ffmpeg parameters. Example with re-encoding:
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.