a simple bash script that uses find, for and redirection

I don’t know why it has taken me this long to have a look at bash. It’s great! I wrote a little script today to list the versions of various Plone packages in a release and I needed somewhere to put it:

#!/bin/bash

# spits out the details from version.txt from a toplevel directory

if [ $# -eq 0 -o $# -gt 2 ]
then
echo “Usage: $0 Directory [filename]”
echo “The directory passed to this script is where it looks for version.txt files.”
echo “The filename is for writing the results to, if it already exists then the script complains.”
echo “If no filename is provided the script writes the results to ‘the Directory name + .txt'”
fi

TLD=$1

# Try to change to the directory or give up
cd $TLD || exit

echo entered `pwd`

#Find all the version.txt files under the directory
VERS=$(find ./ -iname “version.txt” | sort)

#Get the version
for file in $VERS
do
RESULT+=”$file `cat $file`\n”
done

cd ../

#If a filename has been specified use it, otherwise call it something sensible
if [ $# -eq 2 ]
then
OUTPUT=$2
else
OUTPUT=”$1-product-versions.txt”
fi

#It the file already exists don’t overwrite anything, just print out the details
if [ -f $OUTPUT ]
then
echo -e “$OUTPUT already exists, no output has been saved:\n”
echo -e $RESULT
else
echo -e $RESULT >> $OUTPUT
echo -e “Output written to $OUTPUT”
fi

exit 0

Advertisements

1 thought on “a simple bash script that uses find, for and redirection”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s