Last active
April 27, 2026 18:27
-
-
Save kolisee/7155b541d7859a3c0014bfde7430cfc6 to your computer and use it in GitHub Desktop.
Linux ffmpeg flac-to-mp3 converter bash script (with subdirectories)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/env bash | |
| # converts .flac files to .mp3 (320kbps) using ffmpeg | |
| # descends into subdirectories when using maxdepth of 2 or greater (default: 1) | |
| # requirements: bash and ffmpeg | |
| # run this script conveniently by adding an alias to ~/.bashrc | |
| # alias convertflacs="path/to/your/convertflacs.sh" | |
| # usage: | |
| # convertflacs <maxdepth> | |
| # or: | |
| # path/to/your/convertflacs.sh <maxdepth> | |
| # if no depth given, it defaults to 1, | |
| # which means it only converts your current working directory ($PWD) and not the subdirectories. | |
| # it creates "flacs" directory inside every directory (album) that has .flac files | |
| # and moves the .flac files there after converting. | |
| # also skips any "flacs" directory to avoid converting converted files repeatedly. | |
| # also intentionally refrained from using rm incase ffmpeg changes and behaves unexpectedly. | |
| convertflacs_func() | |
| { | |
| [ ! -x "$(command -v ffmpeg)" ] && { echo "convertflacs() ERROR: ffmpeg not found."; return 1; } | |
| local count=0 | |
| local curr_dir dir_name new_file | |
| [[ "$1" =~ ^-h$|^-help$ ]] && { echo "convertflacs() usage: convertflacs <maxdepth>"; return 0; } | |
| depth="${1:-1}" # defaults to 1 if no args given | |
| [ "$depth" -eq "$depth" ] 2>/dev/null | |
| [ $? -ne 0 ] && { echo "convertflacs() ERROR: arg1 has to be an integer."; return 1; } | |
| ((depth < 1)) && { echo "convertflacs() ERROR: arg1 has to be > 0."; return 1; } | |
| while IFS= read -r -d '' file_path; do | |
| [ ! -f "$file_path" ] && { echo "convertflacs() ERROR: no files found."; return 1; } | |
| curr_dir="$(dirname "$file_path")" | |
| dir_name="$(basename "$(dirname "$file_path")")" | |
| new_file="${file_path%.*}.mp3" | |
| if [ ! -f "$new_file" ] && [[ "$dir_name" != "flacs" ]]; then | |
| echo "convertflacs(): converting $file_path" | |
| ffmpeg -nostdin -loglevel error -i "$file_path" -codec:a libmp3lame -b:a 320k "$new_file" && { | |
| [ ! -d "${curr_dir}/flacs" ] && mkdir -p "${curr_dir}/flacs" | |
| mv -n "$file_path" "${curr_dir}/flacs" | |
| count=$((count + 1)) | |
| } | |
| fi | |
| done < <(find "." -maxdepth "$depth" -name "*.flac" -print0) | |
| ((count == 0)) && { echo "convertflacs(): no files converted."; return 0; } | |
| echo "convertflacs(): done converting $count files." | |
| } | |
| convertflacs_func $1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment