1

I'm trying to build an .sh-Script to help me clear a huge gallery folder. This is my first time with bash scripting and it's not working quite right.

Folder Structure is:

gallery/
    gallery1/
        dynamic/
        thumbs/
        oldfile.jpg_backup
        oldfile.jpg
    gallery2/
        dynamic/
        thumbs/
        oldfile.jpg_backup
        oldfile.jpg

.. and so on.

This is how it should work:

  1. Will be run in the main folder called 'gallery'
  2. Goes into every folder (gallery1, gallery2 etc.)
  3. Checks if the subfolder contains another subfolder called thumbs or dynamic, if yes it should delete them
  4. Check if there are files with a ".jpg_backup" extension in the folder
  5. If yes it deletes all regular .jpg files
  6. It renames als .jpg_backups to .jpgs

I tried it this way but im hanging on line "if [DIRECTORY]". This is purley made up since I have no idea how to do that part. Any help is greatly appreciated

for f in ~/gallery/*;
    do

    [ -d /thumbs ] && rm -r thumbs/ && echo Thumbs deleted...

    [ -d /dynamic ] && rm -r dynamic/ && echo Dynamic deleted...


    if [ DIRECTORY == "*.jpg_backup" ]
        then 
            rm *.jpg
            rename 's/.jpg_backup/.jpg/' *
    fi

    done;
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
sparks
  • 79
  • 2
  • 7
  • Cool nice script. But you don't `cd $f` in that script. What should the line `if [ DIRECTORY == "*.jpg_backup" ]` do? It should do the step `4` ? Does [this](https://stackoverflow.com/questions/6363441/check-if-a-file-exists-with-wildcard-in-shell-script) help? `if ls "$f"/*.jpg_backup >/dev/null 2>/dev/null` ? The `[ -d /thumbs` checks for `thumbs` directory in the `/` dire and `rm -r thumbs/` removes thumb directory in current working dir, these are not related... – KamilCuk Feb 22 '19 at 23:39

2 Answers2

0
#!/usr/bin/env bash

set -o errexit
set -o xtrace

for d in gallery/*; do
  rm -vrf "$d/thumbs" "$d/dynamic"
  if [[ -n "$(shopt -s nullglob; echo $d/*.jpg_backup)" ]]; then
    rm -rf "$d"/*.jpg
    for f in "$d"/*.jpg_backup; do
      mv -v "$f" "${f%_backup}"
    done
  fi
done

References:

imsky
  • 3,239
  • 17
  • 16
0

You're not using the $f variable from the loop to process the files and subdirectories in each iteration.

for f in ~/gallery/*;
do
    [ -d "$f/thumbs" ] && rm -r "$f/thumbs" && echo "$f/dynamic" deleted...
    [ -d "$f/dynamic" ] && rm -r "$f/dynamic" && echo "$f/dynamic" deleted...
    if compgen -G "$f/*.jpg_backup" >/dev/null
    then 
        rm "$f"/*.jpg
        rename 's/.jpg_backup/.jpg/' "$f"/*.jpg_backup
    fi
done;

I found the compgen command in Test whether a glob has any matches in bash.

But all this looping seems unnecessary. You can just do:

rm -rf ~/gallery/*/{thumbs,dynamic}
rename -f 's/.jpg_backup/.jpg/' ~/gallery/*/*.jpg_backup

The -f option to rename tells it to allow replacing an existing file, so the rm command isn't needed.

Barmar
  • 741,623
  • 53
  • 500
  • 612