Iterating through subdirectories in bash

How can we iterate over subdirectories of a given directory and get files in these subdirectories in bash. Can I do this with the grep command?

+3
source share
3 answers

This will go into one subdirectory. The inner loop forwill iterate over closed files and directories. The operator ifexcludes directories. You can set options to include hidden files and directories ( shopt -s dotglob).

shopt -s nullglob
for dir in /some/dir/*/
do
    for file in "$dir"/*
    do
        if [[ -f $file ]]
        then
            do_something_with "$file"
        fi
    done
done

It will be recursive. You can limit the depth using the option -maxdepth.

find /some/dir -mindepth 2 -type f -exec do_something {} \;

-mindepth , ( , -maxdepth).

+7
+2

Well, you can do this with grep:

grep -rl ^ /path/to/dir

But why? findit's better.

+2
source

Source: https://habr.com/ru/post/1781777/


All Articles