Search code examples
linuxbashmkdir

Bash script to make a tree directories


I have a script here, this script will list all directories in current working directory and create sub directories to make a directory tree but the problem is it can't create a directory.

Can anyone help me this out ? The script must create a directory in a specific directory and sub-directories

LIST=`ls -D`
for i in $LIST;
do
mkdir -p $i"/Dir3/Dir4/"
done

Solution

  • Don't parse the output of ls.

    Here is one way to "correctly" iterate over directories:

    for dir in */; do
        #       ^-- the trailing slash makes $dir expand to directories only
        [ -d "${dir}" ] || continue
        mkdir -p "${dir}/Dir3/Dir4/"
    done