Reputation: 87
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:
pwd
command for printing out absolute address (i tried so, but unsuccessfully)Upvotes: 1
Views: 188
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
Reputation: 124646
Your script currently cannot work:
rec_search
, but then it seems you mistakenly call rec
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 charactersif
and for
to make it easier to readThe 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