I need to create a script to scan folders in a directory and take the name of each folder, make a .txt file, name it with the name of the folder and put inside that folder.

For example: A directory that has 3 folders in it named "1" "2" and "3" I want to create a .txt file in each folder named with the name of that folder so that folder 1 has "1.txt" in it folder 2 has "2.txt" in it etc..

I managed to do that with this script:

for i in $(ls -d */); do touch "$i $(basename $i).txt" ; done

The problem is I want to do the same thing but with folders that has spaces in their names. For example: If I have a folder named "Test Me" It will give an error saying something like this:

Me: no directory with that name

It will see only the word "Me" and treat it as a folder and not "Test Me" as a whole.

How can I do that ?

Update This is the solution, it is commented below by TAAPSogeking (Thanks again to him) for dir in *; do [ -d "$dir" ] && touch "$dir/$dir.txt"; done

  • ls is only causing problems. In this case you should simply use *, so for i in */; do ...
    – sudodus
    Aug 1, 2022 at 22:40
  • Thanks man, it gave me this error though as the folder name is "Test Me (5656)" `basename: extra operand ‘(5656)’ Aug 1, 2022 at 22:54
  • 2
    let shell replace basename also:for dir in */; do touch $dir${dir%/}.txt; done (@sudodus) Aug 2, 2022 at 3:06

2 Answers 2


Assuming you just want the immediately directories and not all nested sub directories. The following assumes you are currently in the same directories and the directories you want to loop over

for dir in *; do 
    [ -d "$dir" ] && touch -- "$dir/$dir.txt"
  1. This will loop over every file in the current directory
  2. filter for directories (including symlinks to directories).
  3. And then create the requested file in the specified directory

Also you may be interested in shellcheck which point out common errors/bad practices (like the use of ls in this case)

  • I can't thank you enough, I really can't. Thanks a lot. Aug 1, 2022 at 22:55
  • 2
    You don't need the additional check for directories - use */ instead and the glob will expand to only include directories
    – muru
    Aug 2, 2022 at 5:25

With zsh, you could do:

touch -- *(/e['REPLY+=/$REPLY.txt'])

Where the / glob qualifier restricts the glob expansion to files of type directory (change to -/ if you also want to consider symlinks to directories), and the e qualifier evaluates the given code to modify the path (stored in $REPLY). Add the D (for Dot files) qualifier to also do it for hidden directories (. and .. not included in any case).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .