Linux: create random directory/file hierarchy

前端 未结 4 1430
[愿得一人]
[愿得一人] 2020-12-28 23:52

For testing a tool I need a directory with a whole bunch of different Office files in a deep nested structure. I already have the files in a directory, but now need to creat

4条回答
  •  悲哀的现实
    2020-12-29 00:30

    This is a script that generate a random dir structure :

    #!/bin/bash
    
    # Decimal ASCII codes (see man ascii)
    ARR=( {48..57} {65..90} {97..122} )
    
    # Array count
    arrcount=${#ARR[@]}
    
    # return a random string
    get_rand_dir(){
        for ((i=1; i<$((RANDOM%30)); i++)) {
            printf \\$(printf '%03o' ${ARR[RANDOM%arrcount]});
        }
    }
    
    dir=/tmp/
    
    # appending random characters to make a hierarchy
    for ((i=0; i<$((RANDOM%100)); i++)) {
        dir+="$(get_rand_dir)/"
    }
    
    echo $dir
    mkdir -p "$dir"
    
    oldir=$(echo "$dir" | cut -d '/' -f1-3)
    
    while [[ $dir ]]; do
        dir=${dir%/*}
        cd $dir
        for ((i=0; i<$((RANDOM%100)); i++)) {
            mkdir &>/dev/null -p $(get_rand_dir)
        }
    done
    
    tree "$oldir"
    

    OUTPUT

    /tmp/x
    ├── egeDVPW
    ├── iOkr
    ├── l
    ├── o1gye8uF
    ├── q
    │   ├── 4Dlrfagv
    │   ├── 4Yxmoqf
    │   ├── 8LkyIrXA
    │   ├── 8m9kse8s
    │   ├── aV
    │   ├── in
    │   │   ├── 12zdLso68HWlPK
    │   │   │   ├── C
    │   │   │   ├── DOYt8wUW
    │   │   │   ├── FXP
    │   │   │   ├── hFLem8
    │   │   │   ├── hhHIv
    │   │   │   ├── iD87kxs54x04
    │   │   │   ├── oFM
    │   │   │   ├── OjFT
    

    Now you can create an array of dirs :

    shopt -s globstar # require bash4
    dirs=( /tmp/x/** )
    printf '%s\n' ${dirs[@]}
    

    and populate dirs with files randomly. You have enough examples to do so. I've done the most hard work.

提交回复
热议问题