Shell – How to execute a bash command in all possible subdirectories

directorydirectory-structurefilesshell

Let's say my main directory is /home/test

Under it I have lots of subdirectories and under subdirectories still a lots of them and so on.

Example:

/home/test
/home/test/subdir1
/home/test/subdir1/subdir2
/home/test/subdir1/subdir2/subdir3
/home/test/subdir1/subdir2/subdir4
/home/test/subdir1/subdir2/subdir4/subdir5

and so on …

I want a simple script that takes each directory and just runs the pwd command.

Best Answer

Solution Using Parallel

You could use GNU Parallel for a compact, faster solution.

find . -type d -print0 | parallel -0 cd {}'&&' <command-name>

This will work absolutely fine, even for directory names containing spaces and newlines. What parallel does here is that it takes the output from find, which is every directory and then feeds it to cd using {}. Then if changing the directory is successful, a separate command is run under this directory.

Regular Solution using while loop

find "$PWD" -type d | while read -r line; do cd "$line" && <command-name>; done;

Note that $PWD is used here because that variable contains the absolute path of current directory from where the command is being run. If you don't use absolute path, then cd might throw error in the while loop.

This is an easier solution. It will work most of the time except when directory names have weird characters in them like newlines (see comments).

Related Question