Create simple directory or folder
Suppose, you want to create a directory in /home folder named ‘mydir’. Run the following command to create the directory. If no directory exists with the name ‘mydir’ before then the command will be executed without any error. Run ‘ls’ command to check the directory is created or not.
$ ls
Create multiple directories
Run the following command to create multiple directories using ‘mkdir’ command. Three directories, temp1, temp2 and temp3 will be created after executing the command.
$ ls
Create directory when the directory path not exist
Suppose, you want to create a directory in a path, /picture/newdir/test. In the current system, ‘mydir’ directory has no directory or files in it. So, the path is invalid. Run the ‘mkdir’ command with the above path. An error message will appear after running the command.
If you want to create non-exist path forcefully by creating all non-exist directories mentioned in the path from terminal then run ‘mkdir’ command with ‘-p’ option.
Now, check the directories are created or not by running the following commands.
$ ls -R
Create directory with permission
When you create a new directory then a default permission is set for the newly created directory.
Create a new directory and check the default permission by executing following commands. ‘stat’ command is used to check current permission of any existing directory. The default directory permission is ‘rwxr-xr-x’. This indicates directory owner has all permissions, and group users and others users have no write permission.
$ stat newdir1/
‘-m’ option is used to set the directory permission at the time of directory creation. Run the following commands to create a directory with all permissions and check the permission using ‘stat’ command. The output shows all types of users have all permissions.
$ stat newdir2/
Create directory using script
You can test any directory is exist or not by using bash script. Create a bash file and add the following code to create the new directory after testing the directory is exist or not by using ‘-d’ option. If the directory exists then it will show the message, “Directory already exists”, otherwise new directory will be created.
echo -n "Enter the directory name:"
read newdirname
if [ -d "$newdirname" ]; then
echo "Directory already exists" ;
else
`mkdir -p $newdirname`;
echo "$newdirname directory is created"
fi
Run the script and check the directory is created or not.
$ ls
Hope, you will be able to use ‘mkdir’ command with various options more effectively after reading this tutorial. Thank you.