cmd – “if not exist” command in batch file – Stack Overflow

"if not exist" command in batch file

if not exist "%USERPROFILE%.qgis-custom" ( mkdir "%USERPROFILE%.qgis-custom" 2>nul if not errorlevel 1 ( xcopy "%OSGEO4W_ROOT%qgisconfig" "%USERPROFILE%.qgis-custom" /s /v /e )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%.qgis-custom" 2>nul
if not errorlevel 1 ( xcopy "%OSGEO4W_ROOT%qgisconfig" "%USERPROFILE%.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED – As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%qgisconfig" "%USERPROFILE%.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Chaining if commands (and).

The only logical operator directly supported by IF is NOT , so to perform an AND requires chaining multiple IF statements:

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.

:/>  Смена имени компьютера [Hostname] в Windows [GUI/CMD/PowerShell] |

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 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

Parenthesis

Parenthesis can be used to split commands across multiple lines. This enables writing more complex IF… ELSE… commands:

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.

Pipes

When piping commands, the expression is evaluated from left to right, so

IF SomeConditionCommand1 | Command2 is equivalent to:

(IF SomeConditionCommand1 ) | Command2The 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.

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:

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.

:/>  Error Signature: BCCode 10000050 | TechSpot Forums

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”.

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).

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.

IF is an internal command.

You see things; and you say ‘Why?’ But I dream things that never were; and I say ‘why not?’

George Bernard Shaw

Параметры

not
Задает выполнение команды только в случае невыполнения условия.
errorlevelчисло
Условие выполняется, если предыдущая команда, обработанная интерпретатором команд Cmd.exe, завершилась с кодом, равным или большим
числакоманда
Команда, которая должна быть обработана в случае выполнения условия.
строка1==строка2
Условие выполняется, если строки
строка1строка2
совпадают. Строки могут быть заданы явно или могут быть пакетными переменными (например,
%1
). Явно заданные строки нет необходимости заключать в кавычки.
existимя_файла
Условие выполняется, если существует файл с именем
имя_файлаоп_сравнения
Трехзначный оператор сравнения. В следующей таблице перечислены допустимые значения
оп_сравнения/i
Сравнение строк без учета регистра знаков. Параметр
/i
можно использовать в конструкции
string1==string2
команды
if
. Эти сравнения являются общими. Если и
строка1
, и
строка2
состоят из цифр, строки преобразовываются в числа и выполняется сравнение чисел.
cmdextversionчисло
Условие выполняется, только если номер внутренней версии, связанный с расширениями командного процессора Cmd.exe, равен или больше
числа
. первая версия имела номер 1. Номер версии увеличивается на 1 при внесении в расширения командного процессора значительных изменений. Условие с
cmdextversion
не выполняется, если расширения командного процессора запрещены (по умолчанию они разрешены).
definedпеременная
Условие выполняется, если
переменная
определена.
выражение
Команда и все ее параметры для обработке в командной строке при выполнении оператора
else/?
Отображение справки в командной строке.

:/>  Где открыть камеру на ноутбуке

Примеры

Если файл Product.dat не удается найти, появится следующее сообщение:

Синтаксис

if [not] errorlevelчислокоманда [elseвыражение]

if [not] строка1==строка2команда [elseвыражение]

if [not] exist имя_файлакоманда [elseвыражение]

Если расширения командного процессора разрешены, следует использовать следующий синтаксис:

if [/i] строка1оп_сравнениястрока2команда [elseвыражение]

ifcmdextversionчислокоманда [elseвыражение]

ifdefinedпеременнаякоманда [elseвыражение]