1

I'm studying the bash shell and lately understood i'm not getting right recursive calls involving file searching- i know find is made for this but I'm recently asked to implement a certain search this way or another.

I wrote the next script:

#!/bin/bash


function rec_search {
for file in `ls $1`; do
echo ${1}/${item}
if[[ -d $item ]]; then
rec ${1}/${item}
fi
done
}

rec $1

the script gets as argument file and looking for it recursively. i find it a poor solution of mine. and have a few improvement questions:

  1. how to find files that contain spaces in their names
  2. can i efficiently use pwd command for printing out absolute address (i tried so, but unsuccessfully)
  3. every other reasonable improvement of the code
3
  • 1
    Don't use ls! Commented Aug 11, 2016 at 11:48
  • @Inian find is not a built-in command in any shell. Commented Aug 11, 2016 at 12:37
  • @chepner: Agreed it should have been GNU findutils Commented Aug 11, 2016 at 12:40

2 Answers 2

3

Your script currently cannot work:

  • The function is defined as rec_search, but then it seems you mistakenly call rec
  • You need to put a space after the "if" in if[[

There are some other serious issues with it too:

  • for file in `ls $1` goes against the recommendation to "never parse the output of ls", won't work for paths with spaces or other whitespace characters
  • You should indent the body of if and for to make it easier to read

The script could be fixed like this:

rec() {
    for path; do
        echo "$path"
        if [[ -d "$path" ]]; then
            rec "$path"/*
        fi
    done
}

But it's best to not reinvent the wheel and use the find command instead.

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

Comments

0

If you are using bash 4 or later (which is likely unless you running this under Mac OS X), you can use the ** operator.

rec () {
  shopt -s globstar
  for file in "$1"/**/*; do
    echo "$file"
  done
}

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.