Directory. Exists(String) Метод
Определение
Определяет, указывает ли заданный путь на существующий каталог на диске. Determines whether the given path refers to an existing directory on disk.
Параметры
Проверяемый путь. The path to test.
Возвращаемое значение
true , если path ссылается на существующий каталог; значение false , если каталог не существует или если при попытке определить, существует ли указанный каталог. true if path refers to an existing directory; false if the directory does not exist or an error occurs when trying to determine if the specified directory exists.
Примеры
В следующем примере в командной строке принимается массив имен файлов или каталогов, определяется тип имени и обрабатывается соответствующим образом. The following example takes an array of file or directory names on the command line, determines what kind of name it is, and processes it appropriately.
Комментарии
path Параметр может указывать сведения относительного или абсолютного пути. The path parameter is permitted to specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory.
Конечные пробелы удаляются из конца path параметра перед проверкой существования каталога. Trailing spaces are removed from the end of the path parameter before checking whether the directory exists.
path Параметр не учитывает регистр. The path parameter is not case-sensitive.
Если у вас нет разрешения на доступ только для чтения к каталогу, Exists метод возвратит значение false . If you do not have at a minimum read-only permission to the directory, the Exists method will return false .
Метод возвращает значение, если возникла Exists false Ошибка при попытке определить, существует ли указанный файл. The Exists method returns false if any error occurs while trying to determine if the specified file exists. Это может произойти в ситуациях, когда вызываются такие исключения, как передача имени файла с недопустимыми символами или слишком много символов, неудачный или отсутствующий диск или если вызывающий объект не имеет разрешения на чтение файла. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
How to check if directory exists in %PATH%?
How does one check if a directory is already present in the PATH environment variable? Here’s a start. All I’ve managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you’d think it would enumerate all the directories in %PATH%, but it only gets the first one.
Is there a better way of doing this? Something like find or findstr operating on the %PATH% variable? I’d just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.
22 Answers 22
First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.
For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.
From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:
The trailing \ is optional in a path
Most paths work equally well both with and without the trailing \ . The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \ . This is probably the most common practical issue when searching a PATH for a match.
- There is one exception: The relative path C: (meaning the current working directory of drive C) is very different than C:\ (meaning the root directory of drive C)
Some paths have alternate short names
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.
Windows accepts both / and \ as folder separators within a path.
This is not seen very often, but a path can be specified using / instead of \ and it will function just fine within PATH (as well as in many other Windows contexts)
Windows treats consecutive folder separators as one logical separator.
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \ to a path without bothering to check if the trailing \ already exists. But this obviously can cause problems if trying to perform an exact string match.
- Exceptions: Not only is C: , different than C:\ , but C:\ (a valid path), is different than C:\\ (an invalid path).
Windows trims trailing dots and spaces from file and directory names.
«C:\test. » is equivalent to «C:\test» .
The current .\ and parent ..\ folder specifiers may appear within a path
Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\ is equivalent to C:\parent\child
A path can optionally be enclosed within double quotes.
A path is often enclosed in quotes to protect against special characters like , ; ^ & = . Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ; , but the quotes may be present never-the-less.
A path may be fully qualified or relative.
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:
- D: is relative to the current working directory of volume D:
- \myPath is relative to the current working volume (could be C:, D: etc.)
- myPath is relative to the current working volume and directory
It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\ . But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.
So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The
s modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 — 6, and partially addresses issue 7. The
s modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the
s modifier will not append the \ to the path, nor will it convert the path into a valid 8.3 format.
The problem with
s is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with : but not : , where is either \ or / . UNC paths are always fully qualified and must start with \\ . When comparing fully qualified paths we use the
s modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.
There are some additional issues that complicate this problem:
9) Normal expansion is not reliable when dealing with a PATH that contains special characters.
Special characters do not need to be quoted within PATH, but they could be. So a PATH like C:\THIS & THAT;»C:\& THE OTHER THING» is perfectly valid, but it cannot be expanded safely using simple expansion because both «%PATH%» and %PATH% will fail.
10) The path delimiter is also valid within a path name
A ; is used to delimit paths within PATH, but ; can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.
So we can combine the
s modifier and path classification techniques along with my variation of jeb’s PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.
The function can be used like so (assuming the batch file is named inPath.bat):
Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn’t there. This is normally done simply by using something like path %path%;%newPath% . But Issue 9 demonstrates how this is not reliable.
Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped ! will corrupt the value if delayed expansion is enabled.
How to mkdir only if a directory does not already exist?
I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not exist, or suppress the «File exists» error that mkdir throws when it tries to create an existing directory.
How can I best do this?
16 Answers 16
Note that this will also create any intermediate directories that don’t exist; for instance,
will create directories foo , foo/bar , and foo/bar/baz if they don’t exist.
Some implementation like GNU mkdir include mkdir —parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.
If you want an error when parent directories don’t exist, and want to create the directory if it doesn’t exist, then you can test for the existence of the directory first:
This should work:
which will create the directory if it doesn’t exist, but warn you if the name of the directory you’re trying to create is already in use by something other than a directory.
Defining complex directory trees with one command
If you don’t want to show any error message:
If you want to show your own error message:
The old tried and true
will do what you want with none of the race conditions many of the other solutions have.
Sometimes the simplest (and ugliest) solutions are the best.
mkdir foo works even if the directory exists. To make it work only if the directory named «foo» does not exist, try using the -p flag.
This will create the directory named «foo» only if it does not exist. 🙂
mkdir does not support -p switch anymore on Windows 8+ systems.
You can use this:
You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory.
You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.
mkdir -p also allows to create the tree structure of the directory. If you want to create the parent and child directories using same command, can opt mkdir -p
Or if you want to check for existence first:
-e is the exist test for KornShell.
You can also try googling a KornShell manual.
Referring to man page man mkdir for option — p
which will create all directories in a given path, if exists throws no error otherwise it creates all directories from left to right in the given path. Try the below command. the directories newdir and anotherdir doesn’t exists before issuing this command
Correct Usage
mkdir -p /tmp/newdir/anotherdir
After executing the command you can see newdir and anotherdir created under /tmp. You can issue this command as many times you want, the command always have exit(0) . Due to this reason most people use this command in shell scripts before using those actual paths.