How To Create Directories From A Text File In Linux

Create Directories From A Text File In Linux

As you already know, we can create a directory using “mkdir” command in Unix-like systems. Using mkdir command, we can easily create a single or group of directories at a time. It is also possible to create nested directories (a directory inside a directory) with mkdir command. However, If you want to know, there are other ways to create directories too. This brief tutorial describes how to create directories from a text a file from command line in Linux. Read on.

Create Directories From A Text File In Linux

Usually, we create single directory using command:

mkdir dir1

The above command will create a directory called “dir1” in the current working directory.

To create multiple directories, we use:

mkdir dir1 dir2 dir3


mkdir dir{1,2,3}

This command creates three directories namely dir1, dir2, and dir3 in the current working directory.

To create nested directories, we do:

mkdir -p dir1/dir2/dir3

The -p option allows you to create parent directories if the parent directories do not already exists. The above command creates dir2 within dir1 and dir3 within dir2. Here, dir1 is the parent directory to dir2 and dir3. dir2 is the parent directory to dir3. In other words, dir2 is the child directory of dir1 and dir3 is the child directory of dir2 and dir1. Right? Of course yes!

I thought it was only way to create directories from commandline until I came to know about the command xargs. For those wondering, xargs is Linux command which is used to build and execute command lines from standard input.

Now, let us get back to our topic which is creating directories from a text file using xargs.

Say for example, I want to create a the following directory structure.


Have any idea how to create this directory structure? No problem. Just put them in a text file, say mydirectories.txt, one by one as shown below.

Directory structure

Then, run the following command to create the directories.

xargs -I {} mkdir -p "{}" < mydirectories.txt

You can verify whether the directories have been created as you wanted using tree command.

$ tree 
├── Entertainment
│   ├── Movies
│   │   ├── English
│   │   └── Tamil
│   └── Songs
├── Games
├── Linux_Commands
├── Miscellaneous
├── mydirectories.txt
├── Personal
│   └── Bills
├── Study
│   └── Ebooks
└── Tutorials
 └── Videos

14 directories, 1 file

For more details, refer man pages.

man xargs
man mkdir
man tree

Hope you find this useful. We will be posting useful and simple guides about Linux, Open Source everyday. If you like our articles, please spend a moment to share them in your social and professional networks.


Thanks for stopping by!

Help us to help you:

Have a Good day!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.