Bash – Script to loop through folders with numeric names

bashshell-scriptwildcards

I am working on a bash script to compress the images in my WordPress folders. The wordpress folder structure is as follows:

> wp-content/uploads/2014/01/filename.jpg
> wp-content/uploads/2014/02/filename.jpg
> wp-content/uploads/2014/03/filename.jpg
> wp-content/uploads/2014/04/filename.jpg
> 
> i.e. wp-content/uploads/YEAR/MONTH/filename.jpg

In the uploads folder I have a number of other folders (which were created when plugins were installed), so I'm trying to loop through the folders with numeric names only and then compress the images. Here is what I have so far:

DIR_UPLOADS=/home/html/wp-content/uploads/
cd ${DIR_UPLOADS}    
for d in *; do                 # First level i.e. 2014, 2013 folders.
     regx='^[0-9]+$'           # Regular Expression to check for numerics.
     if [[$d =~ $regx]]; then  # Check if folder name is numeric.
       #echo "error: Not a number" >&2; exit 1
       cd $d
       for z in *; do          # Second level i.e. the months folders 01, 02 etc.
        cd $z
        for x in *; do         # Third level the actual file.              
          echo 'Compress Image'
        done
      done
     fi
    done

I'm trying to use reg ex to detect the numeric folders, this isn't quite right, but I think I'm close.

Best Answer

You can use bash extended globbing for this:

shopt -s extglob
DIR_UPLOADS=/home/html/wp-content/uploads/
cd ${DIR_UPLOADS}

for dir in $PWD/+([0-9])/+([0-9]); do
  cd "$dir" &&
    for file in *; do
      echo 'Compress Image'
    done
done

From the man page:

+(pattern-list)
    Matches one or more occurrences of the given patterns

So putting a number range inside will match files/directories. Adding the && conditional will ensure that you only compress images if the match is a directory (and that you actually succeeded in entering it).

Without the extended globbing, you could even just do [1-2][0-9][0-9][0-9]/[0-1][0-9]. This is better than trying a brace expansion as you won't end up attempting to enter directories for every single year/month, even if you have no images from then.

Related Question