Reputation: 4690
I have a folder structure like this:
.
+-- dir
| +-- subdir1
| +-- subdir2
| +-- subdir3
| +-- subdir4
And I want to create an index.html
file inside each subdir
using Bash:
.
+-- dir
| +-- subdir1
| +-- index.html
| +-- subdir2
| +-- index.html
| +-- subdir3
| +-- index.html
| +-- subdir4
| +-- index.html
I can list all of sub directories by using:
.
$ ls dir/*/
And create a file with touch
, then I thought that the correct command would be:
.
$ touch dir/*/index.html
The result: touch: cannot touch 'dir/*/index.html': No such file or directory
How to create a file name for each sub directory using Bash?
Upvotes: 0
Views: 115
Reputation: 295363
touch dir/*/index.html
doesn't workGlobs expand only to things that actually exist, or to the glob expression itself if no matches exist and shell options are all at default configuration. (It's possible to configure this scenario to result in no arguments being generated or in an error condition in bash, using shopt -s nullglob
or shopt -s failglob
).
Thus, if you have dir/subdir1/index.html
, but dir/subdir2/
with no index.html
in it, dir/*/index.html
will expand to only contain dir/subdir1/index.html
, but not any reference at all to subdir2
.
Glob to the things that exist -- the directories -- and tack on the things that don't yourself:
for d in dir/*/; do touch -- "$d/index.html"; done
The --
is needed for the corner case where one of your directories has a name starting with a dash: You don't want -dirname
to be treated as an option to touch
; --
indicates that all future arguments are treated as positional, preventing this circumstance.
Upvotes: 3