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

The output is like :


Where is the problem?

3 Answers 3


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
  • the sed wasn't working for me, so I updated it with this sed -r 's/^\.\///'
    – mfink
    Jan 24, 2018 at 20:21
  • You right I missed a / at the end! Thanks for the HUD. Jan 25, 2018 at 4:25
  • @muru I tried this for d in ./*;do [[ -d "$d" ]] && echo "${d%/}";done and it didn't give the output you suggest, this rather "${d##./}" does the job. Jan 25, 2018 at 4:41

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
  • I see 'maxdepth 1' in the other answer that just appeared. Indeed, I omitted it, adding now for consistency.
    – Maciek
    Jan 11, 2018 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.