Batch Convert Video to MP3 on Ubuntu with FFmpeg
-
Jason Yang - 01 Dec, 2025
- Updated 04 Jan, 2026
- Views —
If you haven’t installed FFmpeg on your Ubuntu machine yet, you can do so easily via the terminal:
sudo apt update
sudo apt install ffmpeg
Here is how to create a script to batch convert video files (MKV, MP4, AVI) to MP3.
1. Create the Script “convert_to_mp3.sh”
Navigate to the directory containing your video files. Create a file named convert_to_mp3.sh using your preferred text editor (like nano or vim) and paste the following code:
#!/bin/bash
for f in *.mkv *.mp4 *.avi; do
# Check if file exists to avoid errors if no files match an extension
[ -f "$f" ] || continue
ffmpeg -i "$f" -vn -ab 192k "${f%.*}.mp3"
done
echo "Conversion complete."
Understanding the Script:
for f in *.mkv *.mp4 *.avi; do: This loop iterates over all files in the current directory that match the specified extensions."$f": Represents the current input file being processed.-vn: Tells FFmpeg to ignore the video stream and extract only the audio.**-ab 192k**: Sets the audio bitrate to 192 kbps (you can also use-b:a 192k).**"${f%.*}.mp3"**: This is the Linux equivalent of Windows’%%~nf. It performs string manipulation to remove the original file extension so the output is namedfilename.mp3instead offilename.mp4.mp3.
The empty-glob gotcha
If the folder has no .avi files, the shell doesn’t quietly skip *.avi — it hands the loop the literal string *.avi. That’s exactly what [ -f "$f" ] || continue guards against: it checks the item is a real file before passing it to ffmpeg. A cleaner alternative is to tell the shell to expand non-matching globs to nothing:
#!/bin/bash
shopt -s nullglob
for f in *.mkv *.mp4 *.avi; do
ffmpeg -i "$f" -vn -ab 192k "${f%.*}.mp3"
done
Either way, the quotes around "$f" matter — drop them and any filename with a space breaks the command.
2. Make Executable and Run
Unlike Windows, Linux requires you to explicitly grant “execute” permissions to a script before running it.
Open your terminal in the directory and run these commands:
# 1. Grant execution permission (only needed once)
chmod +x convert_to_mp3.sh
# 2. Run the script
./convert_to_mp3.sh
The script will now process every video file in the folder and generate a corresponding MP3 file.
This re-encodes each file’s audio to MP3. For the single-file command and the bitrate/VBR options behind -ab, see converting WAV or MP4 to MP3; to cut length rather than convert, see batch trimming MP3s.