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

发布于 2024-08-11 17:03:12 字数 473 浏览 9 评论 0原文

我正在创建一个快速备份脚本,它将一些数据库转储到一个漂亮/整洁的目录结构中,我意识到我需要测试以确保在创建目录之前存在这些目录。我的代码可以工作,但是有更好的方法吗?

[ -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"

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 is there a better way to do it?

[ -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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不及他 2024-08-18 17:03:12

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

-p,--父母

如果存在则没有错误,根据需要创建父目录

所以:

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

You can use the -p parameter, which is documented as:

-p, --parents

no error if existing, make parent directories as needed

So:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
似最初 2024-08-18 17:03:12
mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
长亭外,古道边 2024-08-18 17:03:12

虽然现有答案确实解决了目的,但如果您希望在两个不同的子目录下复制嵌套目录结构,那么您可以这样做:

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

目录下创建以下目录结构:

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

它将在调用它的 来自此链接用于创建SBT 目录结构。

While existing answers definitely solve the purpose, if you’re looking to replicate a nested directory structure under two different subdirectories, then you can do this:

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

It will create the 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 link for creating an SBT directory structure.

木有鱼丸 2024-08-18 17:03:12
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文