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

[ -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参数,它被记录为:

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

So:

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

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

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

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

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

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

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


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