Tuesday, June 12, 2007

One liner to ensure desired directoy hierarchy exists . . .

This tick reveals unix command line depth and expertise:
You have a predefined directory structure hierarchy and before you start the installation/pushing the binaries into them want to make sure you create the directory structure.

How can you write a command line which creates only the directory structure of a given directory. It should not creates the files, just only the directory hierarchy.

Context:

Present directory is /home/narayana/ and it has the below structure:
a
|------- b
|.........|----- c
|.........|.......|---- t1.txt
|.........|
|.........|
|.........|----- d
|.........|.......|---- t2.txt

Create a new directory called programs in /tools/narayana/ and copy only the directory structure to this.

Solution:
Create a t directory and cd to /tools/narayana/ and execute the below command to create this hierarchy.

ls -Rl /home/narayana/a | grep -e '/home/narayana/a.*:$'| cut -d ':' -f 1| awk '{print substr($1, length("/home/narayana/")+1)}'| xargs mkdir -p

This command creates it!!!

Explanation:
------------
Check it by doing recursive listing byls -Rl:
narayana.desktop% pwd
/tools/narayana/
narayana.desktop% ls -Rl
.:
total 4
drwxr-xr-x 3 narayana homedev 4096 Jul 7 13:24 a

./a:
total 4
drwxr-xr-x 4 narayana homedev 4096 Jul 7 13:24 b

./a/b:
total 8
drwxr-xr-x 2 narayana homedev 4096 Jul 7 13:24 c
drwxr-xr-x 2 narayana homedev 4096 Jul 7 13:24 d

./a/b/c:
total 0

./a/b/d:
total 0


Check with the actual directory format:
narayana.desktop% pwd
/home/narayana
narayana.desktop% cd a
narayana.desktop% ls -Rl
.:
total 4
drwxr-xr-x 4 narayana homedev 4096 Jul 7 12:41 b

./b:
total 8
drwxr-xr-x 2 narayana homedev 4096 Jul 7 12:40 c
drwxr-xr-x 2 narayana homedev 4096 Jul 7 12:41 d

./b/c:
total 4
-rw-r--r-- 1 narayana homedev 126 Jul 7 12:41 3

./b/d:
total 4
-rw-r--r-- 1 narayana homedev 9 Jul 7 12:41 4


+ This is useful in many instances where you just want to create the bins into which
a scheduled job can populate the stuff/demographics :)




+

No comments: