LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   recursive searching files in directory matching given name - taking care of links (https://www.linuxquestions.org/questions/linux-newbie-8/recursive-searching-files-in-directory-matching-given-name-taking-care-of-links-802345/)

vikashtulsiyan 04-16-2010 03:22 AM

recursive searching files in directory matching given name - taking care of links
 
Hi,
I am writing a shell script that finds all files named <myFile> in a directory <dir> or any of its subdirectories, recursively. I also need to take care of symbolic links that may form cycles, to avoid infinite loops. I am not supposed to use find command for the same

I started writing the code but got stuck. I thought using recursion may be a smart way, but its not working. Kindly help
Code:

#!/bin/sh


findFiles()
{
thisDIR=$1
#cd $thisDIR
for eachFile in `ls $thiDIR`
do
        if [ "$eachFile" = "$FILE" ]; then
                echo "$FILE found in $thisDIR"
        elif [ -d $eachFile ]; then
                findFiles ${thisDIR}/${eachFile}
        fi
done               

}
if [ $# -ne 2 ]; then
        echo "Please run the script as $0 NameOfFile PathToDirectory"
        exit 1
fi

FILE=$1
DIR=$2

findFiles $DIR


PMP 04-16-2010 06:19 AM

have you looked at grep with -R option

Code:

grep -r <word> dir/*

grail 04-16-2010 06:30 AM

Also with your coding, unless a requirement of the class you are taking, why is FILE treated as a global
variable but DIR is then used as an argument?

catkin 04-16-2010 06:40 AM

Quote:

Originally Posted by vikashtulsiyan (Post 3937318)
Code:

findFiles()
{
    local thisDIR=$1
    #cd $thisDIR
    for eachFile in `ls $thiDIR`  # wrong variable name 
    do
            if [ "$eachFile" = "$FILE" ]; then
                    echo "$FILE found in $thisDIR"
            elif [ -d $eachFile ]; then
                    findFiles ${thisDIR}/${eachFile}
            fi
    done               
}


For recursion to work you need local variables otherwise each new instance of the function changes variables used by its ancestors.

Also you have a mis-typed variable name. Useful to use set -o nounset to make bash tell you about unset variables (including mis-typed names).

grail 04-16-2010 06:59 AM

@catkin - I guess I was being too subtle ;)

bakdong 04-17-2010 01:17 AM

I was playing with this yesterday, declared the function variables as local, but still couldn't get it to go down more than two directories. The directory test line just fails the test.


Code:

  +--test        <--start here
  |
  +--dirone    <--descends to here
    |
    +--dirtwo    <--ignores this dir
    |
    +--dirthree



All times are GMT -5. The time now is 04:51 PM.