Given a file path (e.g. /src/com/mot), how can I check whether mot exists, and create it if it doesn't using Linux or shell scripting??
-
3Does this answer your question? How can I check if a directory exists in a Bash shell script?Josh Correia– Josh Correia2020-12-09 18:02:53 +00:00Commented Dec 9, 2020 at 18:02
Add a comment
|
6 Answers
With bash/sh/ksh, you can do:
if [ ! -d /directory/to/check ]; then
mkdir -p /directory/toc/check
fi
For files, replace -d with -f, then you can do whatever operations you need on the non-existant file.
7 Comments
thiton
You don't actually need the check.
mkdir -p doesn't act on an existing directory.Callie J
That's a fair point. I'll leave it in though as if gives the OP the framework in case they wants to do other things before the
mkdir.Sjoerd
Note that this gives a race condition in the case that the directory is created between the first and second line.
Christian.K
@Sjoerd Indeed, but that race condition (although with a much smaller window of probability) will also occur if you just use
mkdir -p (unless some filesystem implements, and exposes, an atomic check-or-create function call). At least in the code above the mkdir call will not fail if invoked spuriously for an existing directory (because of the -p option provided anyway).William Pursell
@Christian If you want an atomic check-or-create function, look no further than mkdir(2)
|
Well, if you only check for the directory to create it if it does not exist, you might as well just use:
mkdir -p /src/com/mot
mkdir -p will create the directory if it does not exist, otherwise does nothing.
Comments
This is baisc, but I think it works. You'll have to set a few variables if you're looking to have a dynamic list to cycle through and check.
if [ -d /src/com/mot ];
then
echo Directory found
else
mkdir /src/com/mot
fi
Hope that's what you were looking for...
4 Comments
Christian.K
You're missing the ';' after the closing ']' of the if-clause.
William Pursell
@Chirstian The ';' is not needed after the ']', and the ']' is not a closing bracket. In the case of the command '[', the trailing ']' is just an argument to that command. The newline serves the same purpose as the semi-colon.
Christian.K
@WilliamPursell My comment was regarding the first revision of the question, which did not contain a newline after the ']' after the "test" command (or "brackets", sorry for missnaming it), in which case the ';' is required before the
then, isn't it?William Pursell
@christian, yes, either a newline or a ; is required. When I saw the question, the newline was in place.