2

I need to make a linux file search which involves recursion for a project. I got a bit of help making this so I don't understand this code fully only parts of it. Could someone explain what it means and also give a bit of help as to how I would go about getting a user to input a keyword and for this function to search for that keyword in the directories? Thankyou

#!/bin/bash

lookIn() {
    echo $2
    for d in $(find $1 -type d)
    do
        if [ "$d" != "$1" ]
            echo "looking in $d"
            lookIn $d
        fi
    done
}

lookIn
2
  • 2
    At first blush, it would seem that the recursion is unnecessary since find is already traversing the entire directory tree. By "search for that keyword in the directories" what do you mean? Are you looking for file names that match the keyword, or files whose contents contain the keyword? Commented Oct 15, 2013 at 14:16
  • I'm quite new to coding just so you know! I mean that I need to look for file names that match the keyword. Commented Oct 15, 2013 at 14:22

3 Answers 3

3

You only need find. find will traverse the entire directory. Assuming $1 points to the folder you want to search:

read -p "Enter file name to find: " KEYWORD
find $1 -type f -name "$KEYWORD"

If you want to find names that contain the keyword, then use:

find $1 -type f -name "*${KEYWORD}*"

Try this then you can work this into your bigger script (whatever it does).

Sign up to request clarification or add additional context in comments.

Comments

2

TL;DR

Don't use recursion. It may work, but it's more work than necessary; Bash doesn't have tail-call optimization, and it's not a functional programming language. Just use find with the right set of arguments.

Parameterized Bash Function to Call Find

find_name() {    
    starting_path="$1"
    filename="$2"
    find "$1" -name "$2" 2>&-
}

Example Output

Make sure you quote properly, especially if using globbing characters like * or ?. For example:

$ find_name /etc 'pass?d'
/etc/passwd
/etc/pam.d/passwd

2 Comments

Unfortunately part of the project is I have to use recursion :(
@user2882612 Deep recursion in a shell can crash the shell or consume all available memory. You might get away with it for shallow trees, though. YMMV.
1

You don't really need find for recursive file search. grep -r (recursive) will work fine.

See below script:

#!/bin/bash

# change dir to base dir where files are stored for search    
cd /base/search/dir

# accept input from user
read -p "Enter Search Keyword: " kw

# perform case insensitive recursive search and list matched file
grep -irl "$kw" *

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.