Linux mkdir
command is used to create directories. The mkdir command creates directories that don’t exist. But in some cases, the directory may already exist where we do not want to create or recreate the directory. You may ask how can I accomplish this if the directory exists does not run mkdir command?
Directory Existince Check with -p Option
The mkdir command provides the -p
option which is used to parent check. The -p
option also used to create multi level directories by checking parents. We can use the -p in order to check the specified directory existence. If the specifed directory exists the command sliently skips create of the directory. First look how the mkdir command behaves by defualt if the specified directory exist.
$ mkdir var/data/backup
mkdir: cannot create directory ‘data/backup1’: File exists
We can see from the output that if the specified directory exist it returns error like “cannot create directory” etc. It also prints the message “File exists”.
The -p option can be used to check the directory existence and do not create new direrctory if exist and create directory if not exist.
$ mkdir -p /var/data/backup
Directory Existince Check with Bash Script
Bash can be used to check the directory existence and prevent “File exists” error. Generally bash scripts are used to check directory existence and create directory if the directory not exist. The following script checks the directory existence with the conditional.
[ -d /var/data/backup ] || mkdir var/data/backup
Supress “File Exist” Error
Also the mkdir command can be used wihtout any option. The error message can be suppressed and redirected into the /dev/null
device. This do not prints the error code and error message to the standard output.
mkdir /var/data/backup >/dev/null 2>&1