Jump to content

Parsing directories in a shell script


Recommended Posts

I have a bunch of JPGs arranged in directories that describe when the pictures where taken, i.e. there's a directory called "2002", one called "2003" and so on. Under each there are month directories, "2003 June", "2003 July" and so on, and under each of these there are further directories called batch1, batch2 and so forth.

 

Some of the batch directories, however, are empty, and I've been thinking about a script to clean them up. My first step was to write a script to identify the empty directories. Here's my first attempt.

 

#!/bin/sh

cd /home/javaguy/Documents/Photos
DIRS=$(ls -d 2*)

for DIR in $DIRS
do
echo "Changing to directory $DIR"
cd "$DIR"
MONTHS=$(ls -d *)
for MONTH in $MONTHS
do
	echo "Checking $MONTH..."
	if [[ -d '$MONTH' ]]
	then
		echo "Changing to month directory $MONTH"
		cd "$MONTH"
		BATCHES=$(ls -d batch*)
		for BATCH in $BATCHES
		do
			if [[ ! `ls $BATCH` ]]
			then
				echo "$BATCH is empty."
			fi
		done
		cd ..
	fi
done
cd ..
done

 

Here's the problem with this. When it lists all the directories under "2002", it sees directories called "2002 January" and such. I'd like it to check to see if "2002 January" is a directory and, on finding that it is, to cd into it and further check all its subdirectories. But what it does instead is first check to see if "2002" is a directory and then if "January" is a directory (neither exists at that level). How can I make it recognize that "2002 January" is a single directory name?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...