Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if not exist" command in batch file

Tags:

batch-file

cmd

I need to write some code in a windows batch file.

The interested part of this script should create a folder if this folder doesn't exist yet, but, if this folder already exists, it should NOT overwrite the content.

I tried something like this:

if not exist %USERPROFILE%\.qgis-custom (     mkdir %USERPROFILE%\.qgis-custom      xcopy %OSGEO4W_ROOT%\qgisconfig %USERPROFILE%\.qgis-custom /s /v /e ) 

But I'm not sure if I'm doing it right.

Thank you

like image 456
matteo Avatar asked May 19 '14 10:05

matteo


People also ask

Can you use if statements in batch files?

One of the common uses for the 'if' statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the 'if' statement can be done for both strings and numbers.

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

What does 0 |% 0 Do in batch?

What it is: %0|%0 is a fork bomb. It will spawn another process using a pipe | which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).


1 Answers

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.

like image 145
MC ND Avatar answered Oct 02 '22 15:10

MC ND