- Overview
- Part 1 – Getting Started
- Part 2 – Variables
- Part 3 – Return Codes
- Part 4 – stdin, stdout, stderr
- Part 5 – If/Then Conditionals
- Part 6 – Loops
- Part 7 – Functions
- Part 8 – Parsing Input
- Part 9 – Logging
- Part 10 – Advanced Tricks
Computers are all about 1’s and 0’s, right? So, we need a way to handle when some condition is 1, or else do something different
when it’s 0.
The good news is DOS has pretty decent support for if/then/else conditions.
Checking that a File or Folder Exists
IF EXIST "temp.txt" ECHO found
Or the converse:
IF NOT EXIST "temp.txt" ECHO not found
Both the true condition and the false condition:
IF EXIST "temp.txt" (
ECHO found
) ELSE (
ECHO not found
)
NOTE: It’s a good idea to always quote both operands (sides) of any IF check. This avoids nasty bugs when a variable doesn’t exist, which causes
the the operand to effectively disappear and cause a syntax error.
Checking If A Variable Is Not Set
IF "%var%"=="" (SET var=default value)
Or
IF NOT DEFINED var (SET var=default value)
Checking If a Variable Matches a Text String
SET var=Hello, World!
IF "%var%"=="Hello, World!" (
ECHO found
)
Or with a case insensitive comparison
IF /I "%var%"=="hello, world!" (
ECHO found
)
Artimetic Comparisons
SET /A var=1
IF /I "%var%" EQU "1" ECHO equality with 1
IF /I "%var%" NEQ "0" ECHO inequality with 0
IF /I "%var%" GEQ "1" ECHO greater than or equal to 1
IF /I "%var%" LEQ "1" ECHO less than or equal to 1
Checking a Return Code
IF /I "%ERRORLEVEL%" NEQ "0" (
ECHO execution failed
)
<< Part 4 – stdin, stdout, stderr
Part 6 – Loops >>
Проверка существования заданного файла
Второй способ использования команды IF — это проверка существования заданного файла. Синтаксис для этого случая имеет вид:
IF [NOT] EXIST файл команда1 [ELSE команда2]
Условие считается истинным, если указанный файл существует. Кавычки для имени файла не требуются. Приведем пример командного файла, в котором с помощью такого варианта команды IF проверяется наличие файла, указанного в качестве параметра командной строки.
@ECHO OFF IF -%1==- GOTO NoFileSpecified IF NOT EXIST %1 GOTO FileNotExist REM Вывод сообщения о найденном файле ECHO Файл '%1' успешно найден. GOTO :EOF :NoFileSpecified REM Файл запущен без параметров ECHO В командной строке не указано имя файла. GOTO :EOF :FileNotExist REM Параметр командной строки задан, но файл не найден ECHO Файл '%1' не найден.
Проверка наличия переменной среды
Аналогично файлам команда IF позволяет проверить наличие в системе определенной переменной среды:
IF DEFINED переменная команда1 [ELSE команда2]
Здесь условие DEFINED применяется подобно условию EXISTS наличия заданного файла, но принимает в качестве аргумента имя переменной среды и возвращает истинное значение, если эта переменная определена. Например:
@ECHO OFF CLS IF DEFINED MyVar GOTO :VarExists ECHO Переменная MyVar не определена GOTO :EOF :VarExists ECHO Переменная MyVar определена, ECHO ее значение равно %MyVar%
Проверка кода завершения предыдущей команды
Еще один способ использования команды IF — это проверка кода завершения (кода выхода) предыдущей команды. Синтаксис для IF в этом случае имеет следующий вид:
IF [NOT] ERRORLEVEL число команда1 [ELSE команда2]
Здесь условие считается истинным, если последняя запущенная команда или программа завершилась с кодом возврата, равным либо превышающим указанное число.
Составим, например, командный файл, который бы копировал файл my.txt на диск C: без вывода на экран сообщений о копировании, а в случае возникновения какой-либо ошибки выдавал предупреждение:
@ECHO OFF XCOPY my.txt C:\ > NUL REM Проверка кода завершения копирования IF ERRORLEVEL 1 GOTO ErrOccurred ECHO Копирование выполнено без ошибок. GOTO :EOF :ErrOccurred ECHO При выполнении команды XCOPY возникла ошибка!
В операторе IF ERRORLEVEL … можно также применять операторы сравнения чисел, приведенные в табл. 3.2. Например:
IF ERRORLEVEL LEQ 1 GOTO Case1
Замечание.
Иногда более удобным для работы с кодами завершения программ может оказаться использование переменной %ERRORLEVEL%. (строковое представление текущего значения кода ошибки ERRORLEVEL ).
Проверка версии реализации расширенной обработки команд
Наконец, для определения внутреннего номера версии текущей реализации расширенной обработки команд применяется оператор IF в следующем виде:
IF CMDEXTVERSION число команда1 [ELSE команда2]
Здесь условие CMDEXTVERSION применяется подобно условию ERRORLEVEL, но число сравнивается с вышеупомянутым внутренним номером версии. Первая версия имеет номер 1. Номер версии будет увеличиваться на единицу при каждом добавлении существенных возможностей расширенной обработки команд. Если расширенная обработка команд отключена, условие CMDEXTVERSION никогда не бывает истинно.
Организация циклов
В командных файлах для организации циклов используются несколько разновидностей оператора FOR, которые обеспечивают следующие функции:
- выполнение заданной команды для всех элементов указанного множества;
- выполнение заданной команды для всех подходящих имен файлов;
- выполнение заданной команды для всех подходящих имен каталогов;
- выполнение заданной команды для определенного каталога, а также всех его подкаталогов;
- получение последовательности чисел с заданными началом, концом и шагом приращения;
- чтение и обработка строк из текстового файла;
- обработка строк вывода определенной команды.
Цикл FOR … IN … DO …
Самый простой вариант синтаксиса команды FOR для командных файлов имеет следующий вид:
FOR %%переменная IN (множество) DO команда [параметры]
Внимание
Перед названием переменной должны стоять именно два знака процента (%%), а не один, как это было при использовании команды FOR непосредственно из командной строки.
Сразу приведем пример. Если в командном файле заданы строки
@ECHO OFF FOR %%i IN (Раз,Два,Три) DO ECHO %%i
то в результате его выполнения на экране будет напечатано следующее:
Параметр множество в команде FOR задает одну или более текстовых строк, разделенных запятыми, которые вы хотите обработать с помощью заданной команды. Скобки здесь обязательны. Параметр команда [параметры] задает команду, выполняемую для каждого элемента множества, при этом вложенность команд FOR на одной строке не допускается. Если в строке, входящей во множество, используется запятая, то значение этой строки нужно заключить в кавычки. Например, в результате выполнения файла с командами
@ECHO OFF
FOR %%i IN ("Раз,Два",Три) DO ECHO %%i
на экран будет выведено
Параметр %%переменная представляет подставляемую переменную (счетчик цикла), причем здесь могут использоваться только имена переменных, состоящие из одной буквы. При выполнении команда FOR заменяет подставляемую переменную текстом каждой строки в заданном множестве, пока команда, стоящая после ключевого слова DO, не обработает все такие строки.
Замечание.
Чтобы избежать путаницы с параметрами командного файла %0 — %9, для переменных следует использовать любые символы кроме 0 – 9.
Параметр множество в команде FOR может также представлять одну или несколько групп файлов. Например, чтобы вывести в файл список всех файлов с расширениями txt и prn, находящихся в каталоге C:\TEXT, без использования команды DIR, можно использовать командный файл следующего содержания:
@ECHO OFF FOR %%f IN (C:\TEXT\*.txt C:\TEXT\*.prn) DO ECHO %%f >> list.txt
При таком использовании команды FOR процесс обработки продолжается, пока не обработаются все файлы (или группы файлов), указанные во множестве.
Цикл FOR /D … IN … DO …
Следующий вариант команды FOR реализуется с помощью ключа /D:
FOR /D %%переменная IN (набор) DO команда [параметры]
В случае, если набор содержит подстановочные знаки, то команда выполняется для всех подходящих имен каталогов, а не имен файлов. Скажем, выполнив следующий командный файл:
@ECHO OFF CLS FOR /D %%f IN (C:\*.*) DO ECHO %%f
мы получим список всех каталогов на диске C:, например:
C:\Arc C:\CYR C:\MSCAN C:\NC C:\Program Files C:\TEMP C:\TeX C:\WINNT
-
Method 1: Using the IF EXIST Command
-
Method 2: Using Errorlevel
-
Method 3: Using FOR Command
-
Conclusion
-
FAQ
When working with Batch scripts, one common task is checking whether a specific file exists. This can be crucial for ensuring that your script runs smoothly, especially when it relies on external files or configurations. Whether you’re automating backups, processing data, or managing system tasks, knowing how to check for a file’s existence can save you from potential errors and headaches.
In this tutorial, we’ll explore various methods to check if a file exists using Batch scripts. By the end, you’ll have a solid understanding of how to implement these techniques effectively.
Method 1: Using the IF EXIST Command
The simplest way to check if a file exists in a Batch script is by using the IF EXIST command. This command allows you to evaluate whether a specified file is present in the given directory. Here’s how you can use it:
@echo off
set filename="C:\path\to\yourfile.txt"
if exist %filename% (
echo File exists.
) else (
echo File does not exist.
)
In this code, we first set a variable filename that contains the path to the file we want to check. The IF EXIST command evaluates whether the file exists at that location. If it does, the script prints “File exists.” If not, it outputs “File does not exist.” This method is straightforward and effective for checking single files.
Output:
You can easily adapt this code for different file types or paths. Just change the filename variable to point to your desired file. This method is particularly useful in scripts where you need to conditionally execute commands based on the presence of a file.
Method 2: Using Errorlevel
Another approach to check if a file exists is by utilizing the ERRORLEVEL variable. This method is slightly more advanced but can be very effective, especially when you want to handle multiple file checks in a single script.
@echo off
set filename="C:\path\to\yourfile.txt"
rem Try to access the file
type %filename% >nul 2>&1
if errorlevel 1 (
echo File does not exist.
) else (
echo File exists.
)
In this example, the type command attempts to read the file specified by filename. The output is redirected to nul, which means it won’t display any content on the screen. The 2>&1 part ensures that both standard output and error messages are redirected, allowing us to check for errors.
After attempting to read the file, we check the ERRORLEVEL. If it equals 1, it indicates that the file does not exist, and the script will print “File does not exist.” Otherwise, it confirms that the file is present.
Output:
This method is particularly useful when you’re dealing with files that may not be in a standard format or when you want to avoid using the IF EXIST command. It provides a flexible way to handle file existence checks within more complex scripts.
Method 3: Using FOR Command
The FOR command can also be utilized to check for the existence of a file. This method is particularly handy when you want to check multiple files at once or perform actions on them.
@echo off
set filename="C:\path\to\yourfile.txt"
for %%F in (%filename%) do (
echo File exists: %%F
) || (
echo File does not exist.
)
In this script, the FOR command iterates over the specified file. If the file exists, it prints “File exists” along with the file name. If the file does not exist, the || operator triggers the second command, which outputs “File does not exist.”
Output:
File exists: C:\path\to\yourfile.txt
This method can be particularly powerful when combined with wildcards or when checking multiple files. You can easily modify the filename variable to include a wildcard pattern, allowing you to verify the existence of several files in a directory.
Conclusion
In this article, we’ve explored three effective methods for checking if a file exists using Batch scripts: the IF EXIST command, utilizing ERRORLEVEL, and the FOR command. Each method has its advantages, depending on your specific needs and the complexity of your scripts. By mastering these techniques, you can enhance your Batch scripting skills and ensure that your scripts run as intended. Whether you’re automating tasks or managing files, knowing how to check for file existence is a fundamental skill that will serve you well.
FAQ
-
how can I check if a directory exists using Batch?
You can use the sameIF EXISTcommand by specifying the directory path instead of a file path. -
can I check for multiple files at once?
Yes, you can use wildcards with theIF EXISTcommand or iterate through a list of files using theFORcommand. -
what happens if I check for a file that is in use?
The script will still check for the file’s existence and will return the appropriate message based on whether the file is present or not. -
is there a way to suppress error messages in Batch?
Yes, you can redirect error messages tonulusing2>nulto prevent them from displaying in the console. -
can I use these methods in a scheduled task?
Absolutely! These Batch scripts can be executed as part of scheduled tasks in Windows to automate file checks.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Conditionally perform a command.
File syntax IF [NOT] EXIST filename command IF [NOT] EXIST filename (command) ELSE (command)
String syntax IF [/I] [NOT] item1==item2 command IF [/I] item1 compare-op item2 command IF [/I] item1 compare-op item2 (command) ELSE (command)
Error Check Syntax
IF [NOT] DEFINED variable command
IF [NOT] ERRORLEVEL number command
IF CMDEXTVERSION number command
key
item A text string or environment variable, for more complex
comparisons, a variable can be modified using
either Substring or Search syntax.
command The command to perform.
filename A file to test or a wildcard pattern.
NOT perform the command if the condition is false.
== perform the command if the two strings are equal.
/I Do a case Insensitive string comparison.
compare-op can be one of
EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the > and <
symbols are recognised as redirection operators
IF will only parse numbers when one of (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
ERRORLEVEL
There are two different methods of checking an errorlevel, the first syntax ( IF ERRORLEVEL … ) provides compatibility with ancient batch files from the days of Windows 95.
The second method is to use the %ERRORLEVEL% variable providing compatibility with Windows 2000 or newer.
IF ERRORLEVEL n statements should be read as IF Errorlevel >= number
i.e.
IF ERRORLEVEL 0 will return TRUE whether the errorlevel is 0, 1 or 5 or 64
IF ERRORLEVEL 1 will return TRUE whether the errorlevel is 1 or 5 or 64
IF NOT ERRORLEVEL 1 means if ERRORLEVEL is less than 1 (Zero or negative).
This is not very readable or user friendly and does not easily account for negative error numbers.
Using the %ERRORLEVEL% variable is a more logical method of checking Errorlevels:
IF %ERRORLEVEL% NEQ 0 Echo An error was found
IF %ERRORLEVEL% EQU 0 Echo No error found
IF %ERRORLEVEL% EQU 0 (Echo No error found) ELSE (Echo An error was found)
IF %ERRORLEVEL% EQU 0 Echo No error found || Echo An error was found
This allows you to trap errors that can be negative numbers, you can also test for specific errors:
IF %ERRORLEVEL% EQU 64 …
To deliberately raise an ERRORLEVEL in a batch script use the EXIT /B command.
It is possible (though not a good idea) to create a string variable called %ERRORLEVEL% (user variable)
if present such a variable will prevent the real ERRORLEVEL (a system variable) from being used by commands such as ECHO and IF.
Test if a variable is empty
To test for the existence of a command line parameter – use empty brackets like this
IF [%1]==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing
When comparing against a variable that may be empty, we include a pair of brackets [ ] so that if the variable does happen to be empty the IF command still has something to compare: IF [] EQU [] will return True.
You can in fact use almost any character for this a ‘~’ or curly brackets, { } or even the number 4, but square brackets tend to be chosen because they don’t have any special meaning.
When working with filenames/paths you should always surround them with quotes, if %_myvar% contains “C:\Some Path” then your comparison becomes IF [“C:\Some Path”] EQU []
if %_myvar% could contain empty quotes, “” then your comparison should become IF [%_myvar%] EQU [“”]
if %_myvar% will never contain quotes, then you can use quotes in place of the brackets IF “%_myvar%” EQU “”
However with this pattern if %_myvar% does unexpectedly contain quotes, you will get IF “”C:\Some Path”” EQU “” those doubled quotes, while not officially documented as an escape will still mess up the comparison.
Test if a variable is NULL
In the case of a variable that might be NULL – a null variable will remove the variable definition altogether, so testing for a NULL becomes:
IF NOT DEFINED _example ECHO Value Missing
IF DEFINED will return true if the variable contains any value (even if the value is just a space)
To test for the existence of a user variable use SET VariableName, or IF DEFINED VariableName
Test the existence of files and folders
IF EXIST filename Will detect the existence of a file or a folder.
The script empty.cmd will show if the folder is empty or not (this is not case sensitive).
Parenthesis
Parenthesis can be used to split commands across multiple lines. This enables writing more complex IF… ELSE… commands:
IF EXIST filename.txt (
Echo deleting filename.txt
Del filename.txt
) ELSE (
Echo The file was not found.
)
When combining an ELSE statement with parentheses, always put the opening parenthesis on the same line as ELSE.
) ELSE ( This is because CMD does a rather primitive one-line-at-a-time parsing of the command.
When using parentheses the CMD shell will expand [read] all the variables at the beginning of the code block and use those values even if the variables value has just been changed. Turning on DelayedExpansion will force the shell to read variables at the start of every line.
Pipes
When piping commands, the expression is evaluated from left to right, so
IF SomeCondition Command1 | Command2is equivalent to:
(IF SomeCondition Command1 ) | Command2
The pipe is always created and Command2 is always run, regardless whether SomeCondition is TRUE or FALSE
You can use brackets and conditionals around the command with this syntax:
IF SomeCondition (Command1 | Command2)
If the condition is met then Command1 will run, and its output will be piped to Command2.
The IF command will interpret brackets around a condition as just another character to compare (like # or @) for example:
IF (%_var1%==(demo Echo the variable _var1 contains the text demo
Placing an IF command on the right hand side of a pipe is also possible but the CMD shell is buggy in this area and can swallow one of the delimiter characters causing unexpected results.
A simple example that does work:
Echo Y | IF red==blue del *.log
Chaining IF commands (AND).
The only logical operator directly supported by IF is NOT, so to perform an AND requires chaining multiple IF statements:
IF SomeCondition (
IF SomeOtherCondition (
Command_if_both_are_true
)
)
If either condition is true (OR)
This can be tested using a temporary variable:
Set “_tempvar=”
If SomeCondition Set _tempvar=1
If SomeOtherCondition Set _tempvar=1
if %_tempvar% EQU 1 Command_to_run_if_either_is_true
Delimiters
If the string being compared by an IF command includes delimiters such as [Space] or [Comma], then either the delimiters must be escaped with a caret ^ or the whole string must be “quoted”.
This is so that the IF statement will treat the string as a single item and not as several separate strings.
Test Numeric values
IF only parses numbers when one of the compare-op operators (EQU, NEQ, LSS, LEQ, GTR, GEQ) is used.
The == comparison operator always results in a string comparison.
This is an important difference because if you compare numbers as strings it can lead to unexpected results: “2” will be greater than “19” and “026” will be less than “10”.
Correct numeric comparison:
IF 2 GEQ 15 echo “bigger”
Using parentheses or quotes will force a string comparison:
IF (2) GEQ (15) echo “bigger”
IF “2” GEQ “15” echo “bigger”
This behaviour is exactly opposite to the SET /a command where quotes are required.
IF should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647)
C:\> if 2147483646 GEQ 2147483647 (Echo Larger) Else (Echo Smaller)
Smaller ⇨ correct
C:\> if 2147483647 GEQ 2147483648 (Echo Larger) Else (Echo Smaller)
Larger ⇨ wrong due to overflow
C:\> if -2147483649 GEQ -2147483648 (Echo Larger) Else (Echo Smaller)
Larger ⇨ wrong due to overflow
You can perform a string comparison on very long numbers, but this will only work as expected when the numbers are exactly the same length:
C:\> if “2147483647” GEQ “2147483648” (Echo Larger) Else (Echo Smaller)
Smaller ⇨ correct
Wildcards
Wildcards are not supported by IF, so %COMPUTERNAME%==SS6* will not match SS64
A workaround is to retrieve the substring and compare just those characters:
SET _prefix=%COMPUTERNAME:~0,3%
IF %_prefix%==SS6 GOTO they_matched
If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXIST, IF ERRORLEVEL
also the system variable CMDEXTVERSION will be disabled.
IF does not, by itself, set or clear the Errorlevel.
Examples:
IF EXIST C:\logs\*.log (Echo Log file exists) IF EXIST C:\logs\install.log (Echo Complete) ELSE (Echo failed) IF DEFINED _department ECHO Got the _department variable IF DEFINED _commission SET /A _salary=%_salary% + %_commission% IF CMDEXTVERSION 1 GOTO start_process IF %ERRORLEVEL% EQU 2 goto sub_problem2
IF is an internal command.
How to Check file or directory exists in batch programming in windows scripts example program..
Sometimes, we need to delete or copy files to a different folder. To do it, you need to check whether a file exists or not.
DOS provides conditional statements (if else), allowing you to execute commands based on conditional values.
The exist command is used to check if a file or directory exists in a given directory. For example, the exist file command checks if a file exists in the current directory.
The exist command always returns true or false in a conditional context. True means it executes the command inside an if block, while false means it executes the command inside an else block.
The exist command takes a single file name, directory, or an absolute path of a file or directory.
You can also use not exist to check if a file does not exist in the given directory.
if exist test.bat (
echo File exists
) else (
echo File does not exists
)
To check if a given file does not exist:
if not exist c:\test.bat (
echo File does not exists
) else (
echo File exists
)
One important point is that exist only works in the context of conditional statements such as if and else.
If you try to execute the command exist c:\test.bat, it will not work, and prints nothing.
exist c:\test.bat
Conclusion
The if else syntax allows you to perform conditional actions based on true and false values. The exist command is used to check if any file or directory exists in a given directory.
