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



Question:

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?


Solution:1

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  


Solution:2

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.


Solution:3

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
Previous
Next Post »