Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm currently using the following two scripts to create multiple directories and subdirectories. The first script creates '/Dir1/Dir2' and the second script then adds multiple subdirectories to 'Dir2'.

# Creates directories and subdirectories from text file
cat *.txt | xargs -L 1 mkdir -p 

# Lists all directories in current working directory and create subdirectories 
LIST=`ls -D`
for i in $LIST;
mkdir -p $i"/Dir3/Dir4/"

I've combined the two script but the subdirectories Dir3 and Dir4 are created in Dir1 and not Dir2 as intended. With my very limited knowledge of scripting I'm unable to successfully search for the answer and therefore turn to you guys for assistance.

share|improve this question
Before you create the Dir3 and Dir4 you must change the actual directory (cd folder) to the Dir1 and Dir2 respectively. – Lucio Aug 14 '12 at 18:48
I've tried the cd command but it did not do the trick as I'm creating multiple subdirectories. I'm assuming I must be doing some sort of change directory loop before executing the second mkdir command. [please keep in mind that I'm a complete newbie to bash scripting] – ludicerZA Aug 14 '12 at 19:13
Can you tell us, what you are actually trying to achieve? Maybe you are tackling your problem from the wrong side, you know what I mean? – mniess Aug 14 '12 at 19:25
up vote 7 down vote accepted

It is difficult to tell what you are trying to do but I think this does what you want:


cat *.txt | while IFS= read -r line; do
    mkdir -p -- "$line/Dir3/Dir4"

This will read through all the .txt files in the current directory and make a folder with the path ./<line from file>/dir3/dir4.

If this is what you wanted to happen the reason it wasn't working is that $(ls -D) will only list the files in the current directory. It will not recurse down into sub-directories. So even if the first script created a dir1/dir2 directory the second script would only see the dir1 directory.

share|improve this answer
This is the solution to my problem, thank you very much! – ludicerZA Aug 14 '12 at 21:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.