Creating a new directory in Bash is a straightforward process that can be accomplished using the mkdir command. This command stands for `make directory` and allows you to create one or more directories in the file system.
Basic Syntax of the mkdir Command
The basic syntax for the mkdir command is as follows:
mkdir [options] directory_nameIn this syntax:
directory_nameis the name of the directory you want to create.[options]are optional flags that modify the behavior of the command.
Example of Creating a New Directory
Here’s a simple example of creating a new directory:
mkdir my_new_directoryIn this example:
- The command creates a new directory named
my_new_directoryin the current working directory.
Creating Multiple Directories
You can also create multiple directories at once by specifying their names separated by spaces:
mkdir dir1 dir2 dir3In this example:
- The command creates three new directories:
dir1,dir2, anddir3.
Creating Parent Directories
If you want to create a directory along with its parent directories, you can use the -p option:
mkdir -p parent_directory/child_directoryIn this example:
- The command creates
parent_directoryandchild_directoryinside it. Ifparent_directoryalready exists, it will not raise an error.
Checking if a Directory Exists
Before creating a directory, you might want to check if it already exists to avoid errors. You can do this using an if statement:
#!/bin/bash
dir_name=`my_new_directory`
if [ ! -d `$dir_name` ]; then
mkdir `$dir_name`
echo `Directory '$dir_name' created.`
else
echo `Directory '$dir_name' already exists.`
fi
In this example:
- The script checks if the directory
my_new_directoryexists using the-dflag. - If the directory does not exist, it creates it and prints a confirmation message.
- If the directory already exists, it prints a message indicating that.
Conclusion
Creating a new directory in Bash is a simple task that can be accomplished using the mkdir command. By understanding the basic syntax and options available, you can efficiently manage your file system and organize your files into directories. Whether you are creating a single directory or multiple directories at once, the mkdir command is a fundamental tool in Bash scripting and command-line operations.
