mkdir recursively create directories in linux/unix

Creating directories recursively can help us greatly improve efficiency during development.

In linux/unix, we can use the mkdir command to recursively create directories and subdirectories in batches.

There are two methods for mkdir to recursively create directories:

  • Use mkdir -p option
  • Use mkdir -p option plus brace expansion

Syntax

mkdir -p dir/subdir/a/b

mkdir -p dir/subdir/a{1..6}

Examples

Use mkdir -p option

If you want to create multiple nested directories at once, we can use the following command:

mkdir -p dir/subDir/a/b

Obviously, the command will create a tree directory. If some of these directories exist, it is said that they already exist, but other directories do not exist, then mkdir will simply pass them over without error, and create directories under it.

The above command can only create nested directories vertically, so how do we create a vertical and horizontal directory structure?

Use mkdir -p option plus brace expansion

Use brace expansion to create a bunch of directories that follow a single pattern.

For example, when you type mkdir {1..3} and press Enter, it will create three numbered directories in the current directory.

 mkdir {1..3}

With the -p option, you can create vertical and horizontal subdirectories in the current directory. For example, mkdir -p dir/{1..3} will create a subdirectory dir and three subdirectories of the dir directory 1, 2, 3.

Add a Comment

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