4

I´m working on a script that need to read files inside a FIND loop. Something like this :

DIRINI=/Volumes/dados/App\ Data/DATABASE.noindex/30000
for FILE  in `find "$DIRINI"  -type f ` ; do
stat $FILE
stat "$FILE"
stat '$FILE'
done

The problem is : when the foldername has a space inside , i have to put the var $DIRINI inside a "" and this make FIND works , but the other commands inside the loop that use $DIRINI does not work , they split foldername in two use one half in each cicle.

Does someone have an idea of what can i do ? Thanks in advance

1

This is a classic example with the shell performing word splitting. When you assign a variable with spaces the value must be quoted such as, var="foo bar". When the variable var is expanded on the right side of a command the variable must be quoted or the shell splits the variable into two or more arguments.

When you use command substitution in a for loop, the command substitution is expanded as space delimited results. So,

for line in `find dir -type f`

expands into

for line in filename with spaces filename file name with spaces

each word becomes an argument instead of the actual filenames.

Solution 1: is to pipe the results of find into a while read loop:

find "$DIRINI"  -type f | while IFS= read -r line; do
    command "$line"
    command "$line"
done

Solution 2: use process substitution with a while read loop:

while IFS= read -r line; do
    command "$line"
    command "$line"
done < <(find "$DIRINI"  -type f)

Solution 3: just use find:

find "$DIRINI"  -type f -exec command {} \; -exec command {} \;
5

Don‘t loop over results from find, there are too many things which can and will go wrong. Use

find "$DIRINI" -type f -exec stat {} \;

or

find "$DIRINI" -type f -print0 | xargs -0 stat

instead.

  • Thanks Patrix , but this is only a example , i have a whole sequence of commands using this var $FILE inside the FIND loop. I need the var to get the correct path of each files and then use it! – Vilefort Apr 12 '18 at 13:07
  • 1
    @vilefort use xargs or -exec to call a shellscript with your code then. – nohillside Apr 12 '18 at 13:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .