0

I have a music archive with lots of folders and sub-folders (Cover Art etc.) so instead of manually removing hundreds of Folder.jpg, Desktop.ini and Thumb.db files, I decided to do a simple bash script but things got really messy.

I did a simple test by creating dummy folders like this: /home/dummy/sub1 - sub1sub1 sub1sub1sub1 sub1sub1sub2 sub2 - sub2sub1 sub2sub2 sub2sub2sub1

and copied some random .jpg, .mp3, .ini files across these folders. My bash script looks currently like this:

function delete_jpg_ini_db {
    if [[ $f == *.jpg ]]; then
    echo ".jpg file, removing $f"
    gvfs-trash  $f

    elif [[ $f == *.ini ]]; then
    echo ".ini file, removing $f"
    gvfs-trash -f $f

    elif [[ $f == *.db ]]; then
    echo ".db file, removing $f"
    gvfs-trash -f $f

    else echo "not any .jpg, .ini or .db file, skipping $f"
    fi 
}

function iterate_dir {
for d in *; do
    if [ -d $d ]; then
    echo "entering sub-directory: $d" && cd $d
    pwd
    for f in *; do
       if [ -f $f ]; then #check if .jpg, .ini or .db, if so delete
        delete_jpg_ini_db

       elif [ -d $f ]; then #enter sub-dir and iterate again
           if [ "$(ls -A $f)" ]; then
            iterate_dir
            else 
            echo "sub-directory $f is empty!"
             fi
       fi
    done    
    fi  
done
}
pwd
iterate_dir

When I run it, it successfully iterates through sub1, sub1sub1 and sub1sub1sub1, but it halts there instead of going back to home and searching sub2 next.

I am new in Bash scripting, all help is appreciated.. Thanks.

c_b
  • 111
  • 1
  • 1
  • 4

2 Answers2

2

And in one command you can run:

find /home/dummy/sub1 -name "*.jpg" -o -name "*.ini" -o -name "*.db" -delete

And if you want to see which files would be deleted, replace -delete with -print (just filenames) or with -ls (like ls -l output).

Ondrej
  • 101
  • 5
0

here is the changed code....

    function delete_jpg_ini_db {
    if [[ $f == *.jpg ]]; then
    echo ".jpg file, removing $f"
    gvfs-trash  $f

    elif [[ $f == *.ini ]]; then
    echo ".ini file, removing $f"
    gvfs-trash  -f $f

    elif [[ $f == *.db ]]; then
    echo ".db file, removing $f"
    gvfs-trash  -f $f
    else echo "not any .jpg, .ini or .db file, skipping $f"
    fi 
}

function iterate_dir {
for d in *; do
    if [ -d "$d" ]; then
    echo "entering sub-directory: $d" && cd $d
    pwd
    for f in *; do
       if [ -f "$f" ]; then #check if .jpg, .ini or .db, if so delete
         delete_jpg_ini_db

       elif [ -d $f ]; then #enter sub-dir and iterate again
           if [ "$(ls -A $f)" ]; then
             iterate_dir
            else 
            echo "sub-directory $f is empty!"
             fi
       fi

    done
    cd ..   
    fi  
done
}
pwd
iterate_dir

Mistakes

  1. You did have support for file name with space in them
  2. You did not navigate back after your inner for loop..

Try it...

cafebabe1991
  • 4,928
  • 2
  • 34
  • 42