如何使用 Bash 递归创建不存在的子目录? [英] How can I create nonexistent subdirectories recursively using Bash?

查看:23
本文介绍了如何使用 Bash 递归创建不存在的子目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

推荐答案

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

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

-p, --parents

-p, --parents

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

no error if existing, make parent directories as needed

所以:

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

这篇关于如何使用 Bash 递归创建不存在的子目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆