Home > database >  How to loop through subdirectories and files in subdirectories then print file names in bash
How to loop through subdirectories and files in subdirectories then print file names in bash

Time:06-15

Given a root path, I am trying to loop through the sub-directories to loop through the files in each subdirectory and print the names of the files.

The directory structure is like this:

  • Root directory
    • dir2,

      • file{1..10}
    • dir3,

      • file{1..10}
    • dir4

      • file{1..10}

I want to loop through dir2 and print all the filenames in it. Then loop through dir3 and print all the file names...and so on

Here is what I have so far:

#!/bin/bash
#!/bin/sh
cd /the/root/directory
for dir in */
do
        for FILE in dir
        do
             echo "$FILE"
        done > /the/root/directory/filenames.txt
done

This is the output I get in filenames.txt:

dir

My expected output is supposed to be:

file{1..10}
file{1..10}
file{1..10}

I am a beginner to bash scripting...well scripting in general. Any help is greatly appreciated!

CodePudding user response:

You can use the find command, and this will loop through the directories without needing the for loop

my_bash_script.sh:

find * -type d  > filenames.txt

Put this script in the same level of the directories, or you point it to the location by changing the * to the path

note: if it says permission denied in the terminal run this: chmod u x the_script_name.sh

CodePudding user response:

You forgot to expand $dir in your inner loop, so the loop is executing one time with FILE set to the literal string 'dir' instead of the directory name.

After that, you need a globbing pattern to expand to the filenames inside the directory.

Fixed example:

#!/bin/bash
cd /the/root/directory
for dir in */
do
        for FILE in "$dir/"*
        do
             echo "$FILE"
        done > /the/root/directory/filenames.txt
done
  • Related