Linux shell: LOOP for create file in each folder
for dir in */; do touch "$dir/test.txt"done
- There's no need to
cd
into a directory to create a file there. - Don't parse the output of
ls
. The output ofls
is only for looking at. Parsing it will break if your files or directories have names containing literal newlines or spaces. - The pattern
*/
will match any directory in the current directory. - Quote your variable expansions. Your code would break if
IFS
is set to a digit.
If you really need to do a cd
into the directory, do it in a subshell. The changed working directory only affects the subshell and there is no need to cd
back.
for dir in */; do ( cd "$dir" && touch test.txt )done
Let's consider that you have the following 10 folders in your current working directory:
tree ..├── 1├── 10├── 2├── 3├── 4├── 5├── 6├── 7├── 8└── 9
you can run the following command, to create your files:
for d in `find . -mindepth 1 -maxdepth 1 -type d`; do touch "$d"/test.txt; done
OUTPUT:
tree ..├── 1│ └── test.txt├── 10│ └── test.txt├── 2│ └── test.txt├── 3│ └── test.txt├── 4│ └── test.txt├── 5│ └── test.txt├── 6│ └── test.txt├── 7│ └── test.txt├── 8│ └── test.txt└── 9 └── test.txt10 directories, 10 files
Explanations:
find . -mindepth 1 -maxdepth 1 -type d
will get all the folders that are exactly 1 level under your current working folder if you omit -mindepth 1
then you will have a file created in your current working directory since .
will be selected, if you omit -maxdepth 1
then file will be created recursively at any depth level, also -type d
will allow to filter only on directories.
You can then use a loop to create the files or even xargs
command would be enough
You cd
into a directory, but you don't cd
back out. Assuming that the first directory in the list is 1
, your script first changes into 1
, and next tries to change into 1/10
, which does not exist.
You could do a cd -
after touching the file.
Even better, you avoid the cd
altogether and do a touch $i/test.txt
instead.
Of course, the script as written is not very robust: It breaks, if the current directory contains plain files, and it breaks if it contains entries which have spaces in their names - but this is a different issue.