Search code examples
bashrecursiondirectorysubdirectorycd

Is there a way to recursively search through nested subdirectories and execute a command on each one?


I couldn't find a question that involved nested subdirectories. Say I have a directory outline like this:

dir1
 |--dir2
 |    |--a
 |    |--b
 |    |--c
 |--dir3
 |    |--dir4
 |    |--file1
 |    |--file2
 |    |--file3
 |    |--dir5
 |        |--test1
 |        |--test2
 |        |--test3
 |--dir6
 |   |--fileA
 |   |--dir7
 |       |--fileB

Say I had to execute a series of commands in every one of these directories and every subdirectory. Here's the outline of what I need my function to do:

  • CD into a subdirectory if there is one in the current working directory
  • Check to see if there are any subdirectories in the new directory
  • If not, perform a function, otherwise, CD into the next subdirectory
  • If there are no more subdirectories to navigate to, and the function has been completed, CD back into the previous directory and find the next subdirectory, and repeat this process until every subdirectory under dir1 has had the function executed.

Can someone provide me with a Bash script function that will do this? I'm a complete beginner and this is the part of my assignment that's giving me the most trouble. Thanks in advance for your help!


Solution

  • Recursive function, is it that what you are looking for?

    #!/bin/bash
    
    function loop {
    
        for dir in */; do # */ to matach only directories
            if [ -d "$dir" ]; then # check if directory has further directoies
                (cd "$dir" && pwd && loop); # replace pwd with the command to be executed in the directory
            fi 
        done
    }
    
    loop