The ultimate guide for creating and removing directories

One or more directories can be created with a single mkdir command.

1. Creating directories:

Syntax: mkdir [options] dirname

$ mkdir dir1 dir2 dir3
$ ls -l
drwxrwxr-x 2 razvan razvan 4096 2012-05-29 10:45 dir1
drwxrwxr-x 2 razvan razvan 4096 2012-05-29 10:45 dir2
drwxrwxr-x 2 razvan razvan 4096 2012-05-29 10:45 dir3

mkdir dir1 dir2 dir3 creates three directories named “dir1” “dir2” “dir3”.

2. Creating directories with spaces in names:

If you need to create directories containing spaces in their names, use quotes ” “.

$ mkdir "Anakin Skywalker" "Han Solo" "Jabba The Hut"
$ ls -l
drwxrwxr-x 2 razvan razvan 4096 2012-05-29 10:47 Anakin Skywalker
drwxrwxr-x 2 razvan razvan 4096 2012-05-29 10:47 Han Solo
drwxrwxr-x 2 razvan razvan 4096 2012-05-29 10:47 Jabba The Hut

3. Creating directory hierarchives with mkdir -p:

I will create ~/dir1/dir2/dir3/.
$ mkdir -p ~/dir1/dir2/dir3
$ tree -L 1 ~/dir1/
/home/razvan/dir1/
└── dir2
└── dir3

2 directories, 0 files

Usefull mkdir alias:

$ alias mkdir="mkdir -p"

4. Creating directories with customized permissions: mkdir -m

You can set the directory’s permissions before creating it (use the octal method, not rwx):
$ mkdir -m 740 dir
$ ls -ld dir
drwxr----- 2 razvan razvan 4096 2012-05-29 11:22 dir/

Now, let’s learn how to delete directories with the rmdir command:
Syntax: rmdir [options] /path/to/dir

5. Removing empty directories: rmdir

$ rmdir mike
$ ls -l mike
ls: cannot access mike: No such file or directory

6. Remove the non empty directories: rm -r

If you try rmdir on a dir containing files/folders, you will get the following error:

$ rmdir Aa/
rmdir: failed to remove `Aa/': Directory not empty

rm -r is for deleting directories recursively (deleting directories along with the files they contain)

$ rm -r Aa
$ ls -l Aa
ls: cannot access Aa: No such file or directory

Liked it? Take a second to support Geekster on Patreon!
Tagged with: , , , , , ,
Posted in The Linux and Unix Articles!

Leave a Reply

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

*

Support LinuxG via Patreon
Support LinuxG.net on Patreon!
Subscribe

  

Subscribe to get the latest Linux news and how to guides directly on your e-mail!