简体   繁体   中英

Traversing a list and creating directories (OR why is this loop breaking)

I'm trying to create a series of directories using two lists (one for each top level directory, and a one which contains the set of subdirectories each top level will get). I'm using a nested loop to fill the top-level directories one at a time.

Unfortunately, this script only fills the first top level with subdirectories. Why doesn't it continue past the first item in $dirlist?

#! /bin/bash                                                                                                                                             

dirlist=( <a ton of top-level directories> );
combolist=(mpi12_omp1_opt mpi12_omp1 mpi6_omp2 mpi4_omp3 mpi2_omp6 mpi1_omp12);
index1=0;
index2=0;

#This is where I'm trying to create the directories                                                                         
while [ $index1 -lt ${#dirlist[@]} ]
do
    cd ~/bench;
    basedir="bench_"${dirlist[$index1]};
    while [ $index2 -lt ${#combolist[@]} ]
    do
        if [ -d $basedir'/'${combolist[$index2]} ]; then
            DATE=`date +%m-%e-%y`;
            directory=$basedir'/'${combolist[$index2]}'/'$DATE;
            mkdir $directory;
    else #No directory for the combo                                                                                                               
            directory=$basedir'/'${combolist[$index2]};
            mkdir $directory;
    fi
        echo $directory;
    ((index2++));
    done
    ((index1++));
done

Why not iterate over the list directly?

for dir1 in "${dirlist[@]}"
do
    echo $dir1
done

You only initialize index2 to 0 at the start. You need to initialize it to 0 at the start of each iteration:

#This is where I'm trying to create the directories
while [ $index1 -lt ${#dirlist[@]} ]
do
    index2=0
    cd ~/bench;
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM