Asher Yartsev
Asher Yartsev

Reputation: 87

bash finding files in directories recursively

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

Upvotes: 1

Views: 188

Answers (2)

chepner
chepner

Reputation: 531035

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
}

Upvotes: 0

janos
janos

Reputation: 124646

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.

Upvotes: 3

Related Questions