如何使用 Bash 递归创建不存在的子目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1731767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:41:31  来源:igfitidea点击:

How to create nonexistent subdirectories recursively using Bash?

bashshellrecursionsubdirectory

提问by Topher Fangio

I am creating a quick backup script that will dump some databases into a nice/neat directory structure and I realized that I need to test to make sure that the directories exist before I create them. The code I have works, but it seems that there is a better way to do it. Any suggestions?

我正在创建一个快速备份脚本,它将一些数据库转储到一个漂亮/整洁的目录结构中,我意识到我需要在创建目录之前进行测试以确保它们存在。我的代码有效,但似乎有更好的方法来做到这一点。有什么建议?

[ -d "$BACKUP_DIR" ] || mkdir "$BACKUP_DIR"
[ -d "$BACKUP_DIR/$client" ] || mkdir "$BACKUP_DIR/$client"
[ -d "$BACKUP_DIR/$client/$year" ] || mkdir "$BACKUP_DIR/$client/$year"
[ -d "$BACKUP_DIR/$client/$year/$month" ] || mkdir "$BACKUP_DIR/$client/$year/$month"
[ -d "$BACKUP_DIR/$client/$year/$month/$day" ] || mkdir "$BACKUP_DIR/$client/$year/$month/$day"

回答by bmargulies

You can use the -pparameter, which is documented as:

您可以使用该-p参数,该参数记录为

-p, --parents

no error if existing, make parent directories as needed

-p,--父母

如果存在没有错误,请根据需要制作父目录

So:

所以:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

回答by Jonathan Feinberg

$ mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

回答by y2k-shubham

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

虽然现有的答案肯定能解决这个目的,但如果你想在两个不同的子目录下复制嵌套的目录结构,那么你可以这样做

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

它将在调用它的目录下创建以下目录结构

├── main
│?? ├── resources
│?? └── scala
│??     └── com
│??         └── company
└── test
    ├── resources
    └── scala
        └── com
            └── company

The example was taken from this linkfor creating SBT directory structure

该示例取自此链接,用于创建 SBT 目录结构

回答by nitrohuffer2001

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8