gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:37:52 25 4
gpt4 key购买 nike

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

[ -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参数,即documented as :

-p, --parents

no error if existing, make parent directories as needed

所以:

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

关于bash - 如何使用 Bash 递归地创建不存在的子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1731767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com