Bash Script - iterating over output of find

2019-01-09 19:24发布

I have a bash script in which I need to iterate over each line of the ouput of the find command, but it appears that I am iterating over each Word (space delimited) from the find command. My script looks like this so far:

folders=`find -maxdepth 1 -type d`

for $i in $folders
do
    echo $i
done

I would expect this to give output like:

./dir1 and foo
./dir2 and bar
./dir3 and baz

But I am insted getting output like this:

./dir1
and
foo
./dir2
and
bar
./dir3
and
baz

What am I doing wrong here?

3条回答
欢心
2楼-- · 2019-01-09 19:28
folders=`foo`

is always wrong, because it assumes that your directories won't contain spaces, newlines (yes, they're valid!), glob characters, etc. One robust approach (which requires the GNU extension -print0) follows:

while IFS='' read -r -d '' filename; do
  : # something with "$filename"
done < <(find . -maxdepth 1 -type d -print0)

Another safe and robust approach is to have find itself directly invoke your desired command:

find . -maxdepth 1 -type d -exec printf '%s\n' '{}' +

See the UsingFind wiki page for a complete treatment of the subject.

查看更多
Animai°情兽
3楼-- · 2019-01-09 19:28

You can do something like this:

find -maxdepth 1 -type d | while read -r i
do
    echo "$i"
done
查看更多
迷人小祖宗
4楼-- · 2019-01-09 19:31

Since you aren't using any of the more advanced features of find, you can use a simple pattern to iterate over the subdirectories:

for i in ./*/; do
    echo "$i"
done
查看更多
登录 后发表回答