When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.
Create a New Directory ( mkdir ) The first step in creating a new directory is to navigate to the directory that you would like to be the parent directory to this new directory using cd . Then, use the command mkdir followed by the name you would like to give the new directory (e.g. mkdir directory-name ).
In order to check if a file does not exist using Bash, you have to use the “!” symbol followed by the “-f” option and the file that you want to check. Similarly, you can use shorter forms if you want to quickly check if a file does not exist directly in your terminal.
mkdir WILL give you an error if the directory already exists. mkdir -p WILL NOT give you an error if the directory already exists. Also, the directory will remain untouched i.e. the contents are preserved as they were.
First, in bash "[" is just a command, which expects string "]" as a last argument, so the whitespace before the closing bracket (as well as between "!" and "-d" which need to be two separate arguments too) is important:
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
mkdir -p /home/mlzboy/b2c2/shared/db;
fi
Second, since you are using -p switch to mkdir
, this check is useless, because this is what does in the first place. Just write:
mkdir -p /home/mlzboy/b2c2/shared/db;
and thats it.
There is actually no need to check whether it exists or not. Since you already wants to create it if it exists , just mkdir will do
mkdir -p /home/mlzboy/b2c2/shared/db
Simply do:
mkdir /path/to/your/potentially/existing/folder
mkdir will throw an error if the folder already exists. To ignore the errors write:
mkdir -p /path/to/your/potentially/existing/folder
No need to do any checking or anything like that.
For reference:
-p, --parents no error if existing, make parent directories as needed
http://man7.org/linux/man-pages/man1/mkdir.1.html
You need spaces inside the [
and ]
brackets:
#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]
then
mkdir -p /home/mlzboy/b2c2/shared/db
fi
Cleaner way, exploit shortcut evaluation of shell logical operators. Right side of the operator is executed only if left side is true.
[ ! -d /home/mlzboy/b2c2/shared/db ] && mkdir -p /home/mlzboy/b2c2/shared/db
I think you should re-format your code a bit:
#!/bin/bash
if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
mkdir -p /home/mlzboy/b2c2/shared/db;
fi;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With