简体   繁体   中英

How to create a file name for each sub directory using Bash

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?

Why touch dir/*/index.html doesn't work

Globs 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 .

How to fix it

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM