#! /bin/bash # # Filename: findfirst2 # # Programmer: Br. David Carlson # # Date: February 28, 2003 # # This script finds the first file within the directory tree rooted at the first command-line # parameter that matches the target given as the second command-line parameter. Output is # to standard out and gives the full pathname of the located file or a not found message. # Note that this script assumes that it has access to all directories in the above-mentioned # directory tree. If this is not true, you will get error meessages and be left with # temporary files in /tmp. # # Syntax: # findfirst2 StartDir TargetFilename # The following function processes one directory. The input parameters are: # 1 the name of the directory to process # 2 the filename to look for # This recursive function finds the first instance of the desired filename in the directory # tree rooted at the directory given as the first parameter. If a match is found, the complete # pathname for the matching file is printed to standard output and the global variable found # is given the value of 1. onedir() { # Local variables for this function: local TMP local OLDDIR local DIR local fname # bash syntax for adding 1 to a variable: count=$[$count + 1] TMP=/tmp/findfirst.$$.$count OLDDIR="`pwd`" cd "$1" DIR="`pwd`" ls > $TMP sync while read fname do if [ -d "$fname" ] then # Recursive call of the function: onedir "$fname" "$2" if [ "$found" -eq 1 ] then cd "$OLDDIR" rm $TMP return fi elif [ "$fname" = "$2" ] then found=1 echo "${DIR}/$fname" cd "$OLDDIR" rm $TMP return fi done < $TMP rm $TMP cd "$OLDDIR" } # Start of main portion of the script: if [ $# -ne 2 ] then echo "Error: 2 parameters are needed" echo "Syntax: findfirst StartDir TargetFilename" exit 1 fi found=0 count=1 onedir "$1" "$2" if [ "$found" -eq 0 ] then echo "No match was found" fi exit 0