#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 --dir <папка> --count N [--output <файл.m3u>] [--force]" } root="" count=20 output="" force=0 while [[ $# -gt 0 ]]; do case "$1" in --dir) root="${2:-}"; shift 2 ;; --count) count="${2:-}"; shift 2 ;; --output) output="${2:-}"; shift 2 ;; --force) force=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;; esac done if [[ -z "$root" || ! -d "$root" ]]; then echo "Укажите существующую папку через --dir" >&2 exit 2 fi if ! [[ "$count" =~ ^[0-9]+$ ]] || [[ "$count" -eq 0 ]]; then echo "--count должен быть положительным числом" >&2 exit 2 fi if [[ -n "$output" && -e "$output" && "$force" -eq 0 ]]; then echo "Файл уже существует: $output. Добавьте --force." >&2 exit 2 fi mapfile -d '' -t files < <(find "$root" -type f \( -iname '*.mp3' -o -iname '*.flac' -o -iname '*.m4a' -o -iname '*.ogg' -o -iname '*.opus' -o -iname '*.wav' -o -iname '*.mp4' -o -iname '*.mkv' \) -print0) if [[ ${#files[@]} -eq 0 ]]; then echo "Медиафайлы не найдены." >&2 exit 1 fi if [[ "$count" -gt ${#files[@]} ]]; then echo "В папке только ${#files[@]} файлов, уменьшите --count." >&2 exit 2 fi for ((index = ${#files[@]} - 1; index > 0; index--)); do other=$((RANDOM % (index + 1))) temp="${files[index]}" files[index]="${files[other]}" files[other]="$temp" done tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT { echo "#EXTM3U" for ((index = 0; index < count; index++)); do file="${files[index]}" title=$(basename "${file%.*}") relative="${file#"$root"/}" echo "#EXTINF:-1,$title" echo "$relative" done } > "$tmp" if [[ -z "$output" ]]; then cat "$tmp" else mkdir -p "$(dirname "$output")" mv -- "$tmp" "$output" echo "Сохранено: $output" fi