Bash script that creates a directory structure

user668905 picture user668905 · Mar 21, 2011 · Viewed 28.2k times · Source

I've been googling all night trying to find a way to create a script that creates a directory structure. That looks something like this:

/
shared
shared/projects
shared/series
shared/movies
shared/movies/action

You get the point.

The file that the script reads from look like this:

shared backup
shared data
shared projects 
shared projcets series
shared projects movies
shared projects movies action

I want to create a script that reads each line in the file and run the following for each line: If the directory exist, it places itself in the directory and create the structure from there, if The directory doesn’t exist, create it.
When all entries in the row have been preceded by, go back to original directory and read the next line.

My system is Ubuntu 10.10.

So far I’ve done this, but it doesn’t work.

#!/bin/bash

pwd=$(pwd)

for structure in ${column[*]}
do
  if [ $structure ]
  then
    cd $structure
  else
    mkdir $structure
  fi
done

cd $pwd

Answer

littleadv picture littleadv · Mar 21, 2011

You can use mkdir -p shared/projects/movies/action to create the whole tree: it will create shared, then shared/projects, then shared/projects/movies, and shared/projects/movies/action.

So basically you need script that runs mkdir -p $dir where $dir is the leaf directory of your directory tree.