Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a folder exists using a .bat file [closed]

I would like to be able to check if a certain folder (FolderA) exists and if so, for a message to be displayed and then the batch file to be exited.

If FolderA does not exist, I would then like to check if another folder (FolderB) exists. If FolderB does not exist, a message should be displayed and the folder should be created, and if FolderB does exist, a message should be displayed saying so.

Does anybody have any idea on the code I could simply use on notepad to create a batch file to allow me to do this?

All of this needs to be done in one .bat file.

like image 718
user3179825 Avatar asked Jan 10 '14 00:01

user3179825


People also ask

How do you check if a directory exists in Windows?

$Folder = 'C:\Windows' "Test to see if folder [$Folder] exists" if (Test-Path -Path $Folder) { "Path exists!" } else { "Path doesn't exist." } This is similar to the -d $filepath operator for IF statements in Bash. True is returned if $filepath exists, otherwise False is returned.


2 Answers

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

official documentation for if

like image 178
09stephenb Avatar answered Oct 19 '22 06:10

09stephenb


I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

like image 43
Cosmin Vană Avatar answered Oct 19 '22 07:10

Cosmin Vană