Reputation: 401
I have a custom bash test function
main () {
list=$1
for i in ${list}; do
echo $i
done
}
which I am trying to call as:
main `find . -name hello`
but it is only echoing the first file passed in the list. The original output of find . -name hello
is
./world1/hello
./world2/hello
./world3/hello
./world4/hello
./world5/hello
./world6/hello
./world7/hello
./world8/hello
How can I make sure the whole list is passed?
Thanks!
Upvotes: 1
Views: 395
Reputation: 85800
Use a proper Process-Substitution syntax to loop over files, and you don't need a function if you are looking to do a certain action on each of the files from find
output, just do
#!/bin/bash
while IFS= read -r file
do
echo "$file"
# Your other actions on "$file" go here
done < <(find . -type f -name "hello")
(or) if you are afraid of having special characters in file-names like a space or any of the meta-characters, use the -print0
option if it is supported (GNU findutils
package) to separate the files on \0
de-limiter and read it back with the same de-limiter.
while IFS= read -r -d '' file
do
echo "$file"
# Your other actions on "$file" go here
done < <(find . -type f -name "hello" -print0)
I just simply do NOT recommend using function this-way, but you can do something like,
function findRead() {
while IFS= read -r file
do
echo "$file"
# Your other actions on "$file" go here
done <<<"$1"
}
findRead "$(find . -type f -name "hello")"
(or) more-simply just do,
function findRead() {
for file in "$1"
do
echo "$file"
done
}
findRead "$(find . -type f -name "hello")"
The key here is to double-quote the $(..)
command-substitution that returns the output of find
, to preserve the new-line characters which are then fed to your custom function.
Upvotes: 2