Ubuntu: How to write out all directory names into a text file


I want to make a list of my subdirectories. When I execute the following for loop, the first directory name occurs two times

for d in */; do       echo $d >> directories.txt  done  

The output is like :

ONE/  TWO/  ONE/  

Where is the problem?


Improving you current code, this command should be helpful:

for d in ./*;do [[ -d "$d" ]] && echo "$d" >> dir.txt; done  

To remove the ./ from the output:

for d in ./*;do [[ -d "$d" ]] && echo "${d##./}" >> dir.txt; done  


You are appending the entries (>>) where you must be overwriting them (>). It is better to use find. To find all subdirectories recursively, use

find . -type d > directories.txt  

To find subdirectories only in the current directory, use

find . -type d -maxdepth 1 > directories.txt  

-type d instructs find to list only directory files.


What surprises me is the lack of a semicolon (;) in your solution, does your problem persist when you do:

for d in *; do echo $d >> directories.txt; done  

? It works for me fine. Also, are you sure you run it in bash? Finally, the ">>" might be the problem, you might be appending directories' names several times.

Not to mention that if you want to list directories only (not files) you could rather do:

for d in `find . -type d -maxdepth 1`; do echo $d >> directories.txt; done  

or even simpler:

find . -type d -maxdepth 1 > directories.txt  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »