C4stor
C4stor

Reputation: 8026

Looping through "find" result in bash

I'm trying to loop through a bunch of files in a bash script, in particular all jar in my hive maven repo.

I wrote the following code :

for f in $(find /home/c4stor/.m2/repository/org/apache/hive/  -iname '*.jar'); do
  echo "Jar found :":$f;
done

When I execute this in my terminal, I have the following result :

Jar found :/home/c4stor/.m2/repository/org/apache/hive/hive-serde/0.10.0-cdh4.2.1/hive-serde-0.10.0-cdh4.2.1.jar
Jar found :/home/c4stor/.m2/repository/org/apache/hive/hive-common/0.9.0/hive-common-0.9.0.jar
(etc....)

When I run my bash script with the exact same content, it goes like this :

Jar found :/home/c4stor/.m2/repository/org/apache/hive/hive-serde/0.10.0-cdh4.2.1/hive-serde-0.10.0-cdh4.2.1.jar /home/c4stor/.m2/repository/org/apache/hive/hive-common/0.9.0/hive-common-0.9.0.jar (etc....)

i.e the for is looping on a single element compound of all the filepath concatenated. Which is not what I would have desired.

Does anyone have a clue : 1. Why it is behaving this way ? 2. How to have the script behave like the terminal ?

Thanks :) C4stor

Upvotes: 0

Views: 130

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Why it is behaving this way ?

for depends on $IFS. You've changed $IFS and hence how for works.

How to have the script behave like the terminal ?

find ... -print0 | while read -d $'\0' f
do
   ...
done

or...

while read -d $'\0' f
do
   ...
done < <(find ... -print0)

Upvotes: 5

Related Questions