How to write out all directory names into a text file
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