Search code examples
bashmp3

Script that will search for MP3 using id3


I want to create a script that will use one of 4 id tags to search for the MP3 file on the drive. Up to this point i managed to create something like this, but it doesn't really work at all. Could someone suggest me what to fix?

#!/bin/bash    

while getopts ":atbg:" opt; do
case $opt in
a) artist=${OPTARG}
;;
b) album=${OPTARG}
;;
t) title=${OPTARG}
;;
g) genre=${OPTARG}
;;
esac
done
find . -name '*.mp3' -print0 | while read -d $'\0' file 
do
    checkere=0
    if [ "$album" != NULL ]
    then
        if [ !($(id3info "$file" | grep '$artist' sed -e 's/.*: //g')) ]
        then
            $checkere=1
        fi
    fi
    if [ "$title" != NULL ]
    then
        if [ !($(id3info "$file" | grep '$title' sed -e 's/.*: //g')) ]
        then
            $checkere=1
        fi
    fi
    if [ "$album" != NULL ]
    then
        if !($(id3info "$file" | grep '$album' sed -e 's/.*: //g'))
        then
            $checkere=1
        fi
    fi
    if [ "$genre" != NULL ] 
    then
        if !($(id3info "$file" | grep '$genre' sed -e 's/.*: //g'))
        then
            $checkere=1
        fi
    fi
    if [ $checkere -eq 0 ]
    then
        echo $file          
    fi
done

Solution

  • #!/bin/bash
    # Process command line args
    while getopts a:b:t:g: arg ; do case $arg in
        a) artist=${OPTARG} ;;
        b) album=${OPTARG} ;;
        t) title=${OPTARG} ;;
        g) genre=${OPTARG} ;;
        :) echo "${0##*/}: Must supply an argument to $OPTARG." ; exit 1 ;;
        \?) echo "Invalid option. Abort" ; exit 1 ;;
        esac
        done
    shift $(($OPTIND - 1))
    [ "$#" -eq 0 ] || { echo "Incorrect usage" ; exit 1 ; }
    
    # Find matching files
    find . -name '*.mp3' -print0 |
    while read -r -d $'\0' file
    do
        info=$(id3info $file)
        [ "$artist" ] && { echo "$info" | grep -q "=== TPE1 (Lead performer(s)/Soloist(s)): $artist$" || continue ; }
        [ "$album" ] && { echo "$info" | grep -q "=== TALB (Album/Movie/Show title): $album$" || continue ; }
        [ "$title" ] && { echo "$info" | grep -q "=== TIT2 (Title/songname/content description): $title$" || continue ; }
        [ "$genre" ] && { echo "$info" | grep -q "=== TCON (Content type): $genre$" || continue ; }
        echo "$file"
    done  
    

    Sample usage:

    mp3search -a "The Rolling Stones" -t "Let It Bleed"